Planned update

+ Bugfixes
- Jumps on distance < ship length in direction
+ Players assignment to warpcore
This commit is contained in:
Anus 2013-02-10 22:00:38 +04:00
parent 5457ab8d8d
commit d56d476149
10 changed files with 557 additions and 142 deletions

View file

@ -1,24 +1,28 @@
package cr0s.WarpDrive;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.Random;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public class BlockReactor extends BlockContainer {
public class BlockReactor extends BlockContainer {
BlockReactor(int id, int texture, Material material) {
super(id, texture, material);
}
@Override
public String getTextureFile () {
return CommonProxy.BLOCK_TEXTURE_OFFLINE;
return CommonProxy.BLOCK_TEXTURE;
}
@Override
public TileEntity createNewTileEntity(World var1) {
return new TileEntityReactor(var1);
return new TileEntityReactor();
}
/**
@ -37,5 +41,36 @@ public class BlockReactor extends BlockContainer {
public int idDropped(int par1, Random par2Random, int par3)
{
return this.blockID;
}
}
/**
* Called upon block activation (right click on the block.)
*/
@SideOnly(Side.SERVER)
@Override
public boolean onBlockActivated(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer, int par6, float par7, float par8, float par9)
{
if (FMLCommonHandler.instance().getEffectiveSide().isServer()) {
TileEntityReactor reactor = (TileEntityReactor)par1World.getBlockTileEntity(par2, par3, par4);
if (reactor != null){
reactor.attachPlayer(par5EntityPlayer);
par5EntityPlayer.sendChatToPlayer("[WarpCore] Attached players: " + reactor.getAttachedPlayersList());
}
}
return false;
}
/**
* Called when the block is clicked by a player. Args: x, y, z, entityPlayer
*/
//@SideOnly(Side.SERVER)
@Override
public void onBlockClicked(World par1World, int par2, int par3, int par4, EntityPlayer par5EntityPlayer) {
TileEntityReactor reactor = (TileEntityReactor)par1World.getBlockTileEntity(par2, par3, par4);
if (reactor != null){
par5EntityPlayer.sendChatToPlayer(reactor.getCoreState());
}
}
}

View file

@ -3,8 +3,7 @@ package cr0s.WarpDrive;
import cpw.mods.fml.common.registry.EntityRegistry;
public class CommonProxy {
public static final String BLOCK_TEXTURE_OFFLINE = "CORE_OFFLINE.png";
public static final String BLOCK_TEXTURE_ONLINE = "CORE_ONLINE.png";
public static final String BLOCK_TEXTURE = "WarpDrive.png";
public void registerJumpEntity() {
EntityRegistry.registerModEntity(EntityJump.class, "EntityJump", 1, WarpDrive.instance, 80, 1, false);

View file

@ -6,8 +6,12 @@ import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemInWorldManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.src.ModLoader;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ChunkCoordinates;
@ -51,10 +55,16 @@ public class EntityJump extends Entity {
boolean isJumping = false;
int currentIndexInShip = 0;
private final int BLOCKS_PER_TICK = 500;
private final int BLOCKS_PER_TICK = 1000;
private List entityOnShip;
AxisAlignedBB axisalignedbb;
private boolean fromSpace, toSpace;
private EntityPlayer fakePlayer;
public EntityJump(World world) {
super(world);
}
@ -105,51 +115,180 @@ public class EntityJump extends Entity {
killEntity("Entity is disabled or Y-coord error! Cannot jump.");
return;
}
// Пропустить тик, ожидая генерации чанков
//if (!checkForChunksGeneratedIn(getTargetWorld())) {
// return;
//}
if (!isJumping) {
System.out.println("[JE] Preparing to jump...");
axisalignedbb = AxisAlignedBB.getBoundingBox(Xmin, minY, Zmin, Xmax, maxY, Zmax);
this.toSpace = (dir == -1 && (maxY + distance > 255) && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID);
this.fromSpace = (dir == -2 && (minY - distance < 0) && worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID);
prepareToJump();
} else {
if (currentIndexInShip >= ship.length-1) {
isJumping = false;
finishJump();
} else {
moveShip();
} else {
moveEntitys(axisalignedbb, distance, dir, true);
moveShip();
}
}
}
public World getTargetWorld() {
if (toSpace) {
return DimensionManager.getWorld(WarpDrive.instance.spaceDimID);
} else if (fromSpace) {
return DimensionManager.getWorld(0);
} else {
return this.worldObj;
}
}
public void lockWorlds() {
getTargetWorld().editingBlocks = true;
// При прыжках между измерениями необходимо блокировать текущий мир
// Для предотвращения рассыпания проводов на корабле
if (getTargetWorld().provider.dimensionId != worldObj.provider.dimensionId) {
worldObj.editingBlocks = true;
}
}
public void unlockWorlds() {
getTargetWorld().editingBlocks = false;
// При прыжках между измерениями необходимо блокировать оба мира
// Для предотвращения рассыпания проводов на корабле
if (getTargetWorld().provider.dimensionId != worldObj.provider.dimensionId) {
worldObj.editingBlocks = false;
}
}
/**
* Установка или удаление блоков под игроками для предотвращения их падения
* @param removeBlocks удалять блоки
*/
public void setBlocksUnderPlayers(boolean removeBlocks) {
List list = this.entityOnShip;
if (list != null) {
for (Object obj : list) {
if (!(obj instanceof MovingEntity)) {
continue;
}
MovingEntity me = (MovingEntity)obj;
Entity entity = me.entity;
if (entity instanceof EntityPlayer) {
if (!removeBlocks) {
worldObj.setBlock(me.oldX, me.oldY - 2, me.oldZ, Block.dirt.blockID);
} else
{
if (worldObj.getBlockId(me.oldX, me.oldY - 2, me.oldZ) == Block.dirt.blockID) {
worldObj.setBlock(me.oldX, me.oldY - 2, me.oldZ, 0);
}
}
}
}
}
}
/**
* Проверка на существование чанков в точке назначения прыжка
* Если чанки не загружены или не существуют, то происходит их загрузка или генерация
* @param world Мир, в котором осуществляется проверка
* @return Результат проверки
*/
public boolean checkForChunksGeneratedIn(World w) {
for (int y = minY; y <= maxY; y++) {
for (int x = Xmin; x <= Xmax; x++) {
for (int z = Zmin; z <= Zmax; z++) {
final int newX = getNewXCoord(x, 0, z, this.distance, this.dir);
final int newZ = getNewZCoord(x, 0, z, this.distance, this.dir);
int chunkX = newX >> 4;
int chunkZ = newZ >> 4;
if (!w.getChunkProvider().chunkExists(chunkX, chunkZ)) {
System.out.println("[JE] Need to generate chunk at (" + chunkX + "; " + chunkZ + "). Creating fake player");
w.getChunkProvider().provideChunk(chunkX, chunkZ);
return false;
}
}
}
}
return true;
}
public void messageToAllPlayersOnShip(String msg) {
List list = this.entityOnShip;
if (list != null) {
for (Object obj : list) {
if (!(obj instanceof MovingEntity)) {
continue;
}
MovingEntity me = (MovingEntity)obj;
Entity entity = me.entity;
if (entity instanceof EntityPlayer) {
((EntityPlayer)entity).sendChatToPlayer("[WarpCore] " + msg);
}
}
}
}
public void prepareToJump() {
// Блокируем миры
if (dir == -1 && maxY >= 255 && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) {
DimensionManager.getWorld(WarpDrive.instance.spaceDimID).editingBlocks = true;
} else if (dir == -2 && (minY - distance < 0) && worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID) {
System.out.println("[JE] Jump FROM SPACE (" + (minY - distance) + ")");
DimensionManager.getWorld(0).editingBlocks = true;
} else {
worldObj.editingBlocks = true;
boolean betweenWorlds = false;
// Блокируем мир
lockWorlds();
betweenWorlds = fromSpace || toSpace;
saveEntitys(axisalignedbb);
System.out.println("[JE] Saved " + entityOnShip.size() + " entities from ship");
if (dir != -2 && dir != -1) {
messageToAllPlayersOnShip("Jumping in direction " + dir + " degrees to distance " + distance + " blocks ");
} else if (dir == -1) {
messageToAllPlayersOnShip("Jumping UP to distance " + distance + " blocks ");
} else if (dir == -2) {
messageToAllPlayersOnShip("Jumping DOWN to distance " + distance + " blocks ");
}
distance = getPossibleJumpDistance();
if (distance <= 0 && (dir != -1 && worldObj.provider.dimensionId != 0) && (dir != -2 && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID)) {
if (!betweenWorlds) {
distance = getPossibleJumpDistance();
} else {
distance = 0;
}
if (distance <= this.shipLength && (!fromSpace && !toSpace)) {
killEntity("Not enough space for jump.");
messageToAllPlayersOnShip("Not enough space for jump!");
return;
}
if (!checkForBedrockOnShip()) {
killEntity("Is bedrock on the ship. Aborting.");
messageToAllPlayersOnShip("Is bedrock on the ship. Aborting.");
return;
}
int shipSize = getRealShipSize();
saveShip(shipSize);
AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(Xmin, minY, Zmin, Xmax, maxY, Zmax);
saveEntitys(axisalignedbb);
System.out.println("[JE] Saved " + entityOnShip.size() + " entities from ship");
removeShip();
setBlocksUnderPlayers(false);
isJumping = true;
this.currentIndexInShip = 0;
@ -159,20 +298,11 @@ public class EntityJump extends Entity {
* Закончить прыжок: переместить Entity, разблокировать мир и удалить себя
*/
public void finishJump() {
AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(Xmin, minY, Zmin, Xmax, maxY, Zmax);
boolean fromSpace = (worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID && minY - distance < 0 && dir == -2);
boolean toSpace = (worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID && maxY >= 255);
moveEntitys(axisalignedbb, distance, dir, toSpace, fromSpace);
// Разблокируем миры
if (dir == -1 && maxY >= 255 && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) {
DimensionManager.getWorld(WarpDrive.instance.spaceDimID).editingBlocks = false;
} else if (dir == -2 && (minY - distance < 0) && worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID) {
DimensionManager.getWorld(0).editingBlocks = false;
} else {
worldObj.editingBlocks = false;
}
moveEntitys(axisalignedbb, distance, dir, false);
setBlocksUnderPlayers(true);
// Разблокируем мир
unlockWorlds();
// Прыжок окончен
killEntity("");
@ -232,7 +362,6 @@ public class EntityJump extends Entity {
}
System.out.println((new StringBuilder()).append("[JUMP] Ship saved: ").append((new StringBuilder()).append(ship.length).append(" blocks")).toString());
}
/**
@ -244,22 +373,22 @@ public class EntityJump extends Entity {
System.out.println("[JE] Moving ship part: " + currentIndexInShip + "/" + ship.length + " [btm: " + blocksToMove + "]");
// 1. Прыжок в космос
if (dir == -1 && maxY >= 255 && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) {
if (toSpace) {
for (int index = 0; index < blocksToMove; index++) {
this.currentIndexInShip++;
moveBlockToSpace(currentIndexInShip, distance, dir);
this.currentIndexInShip++;
}
// 2. Прыжок из космоса
} else if (dir == -2 && (minY - distance < 0) && worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID) {
} else if (fromSpace) {
for (int index = 0; index < blocksToMove; index++) {
this.currentIndexInShip++;
moveBlockFromSpace(currentIndexInShip, distance, dir);
this.currentIndexInShip++;
}
// 3. Обычный прыжок
} else {
for (int index = 0; index < blocksToMove; index++) {
this.currentIndexInShip++;
moveBlock(currentIndexInShip, distance, dir);
this.currentIndexInShip++;
}
}
}
@ -277,10 +406,7 @@ public class EntityJump extends Entity {
int blowPoints = 0; // Вероятность взрыва ядра реактора
while (true) {
if (testDistance <= this.shipLength) {
break;
}
// Проверка, достаточно ли места в точке назначения прыжка
canJump = checkMovement(testDistance);
if (canJump) {
@ -290,9 +416,10 @@ public class EntityJump extends Entity {
blowPoints++;
testDistance--;
}
// Взрываем точку столкновения с препятствием, если это явно не стыковка или прыжок на землю из космоса
if (blowPoints > 5 && this.dir != -1 && !(this.dir == -2 && worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID)) {
// Взрываем точку столкновения с препятствием, если это явно не стыковка или прыжок в вертикальной плоскости
if (blowPoints > 5 && (this.dir != -1 && this.dir != -2)) {
messageToAllPlayersOnShip(" [COLLISION] at (" + blowX + "; " + blowY + "; " + blowZ + ")");
worldObj.createExplosion((Entity) null, blowX, blowY, blowZ, Math.min(4F * 30, 4F * (distance / 2)), true);
}
@ -361,13 +488,21 @@ public class EntityJump extends Entity {
Entity entity = (Entity)o;
MovingEntity movingentity = new MovingEntity(entity, MathHelper.floor_double(entity.posX), MathHelper.floor_double(entity.posY), MathHelper.floor_double(entity.posZ));
// Добавим в список Entity
entityOnShip.add(movingentity);
}
}
public boolean moveEntitys(AxisAlignedBB axisalignedbb, int distance, int direction, boolean toSpace, boolean fromSpace) {
/**
* Перемещение сущностей вместе с кораблем
* @param axisalignedbb область корабля
* @param distance расстояние перемещения
* @param direction направление перемещения
* @param restorePositions восстановление старых позиций для предотвращения выпадения, либо перемещение на новую
* @return
*/
public boolean moveEntitys(AxisAlignedBB axisalignedbb, int distance, int direction, boolean restorePositions) {
List list = this.entityOnShip;
if (list != null) {
@ -387,17 +522,23 @@ public class EntityJump extends Entity {
int oldEntityZ = me.oldZ;
int newEntityX, newEntityY, newEntityZ;
newEntityX = oldEntityX;
newEntityY = oldEntityY;
newEntityZ = oldEntityZ;
if (!toSpace && !fromSpace)
if (!restorePositions && !toSpace)
{
newEntityX = getNewXCoord(oldEntityX, oldEntityY, oldEntityZ, distance, direction);
newEntityY = getNewYCoord(oldEntityX, oldEntityY, oldEntityZ, distance, direction);
newEntityZ = getNewZCoord(oldEntityX, oldEntityY, oldEntityZ, distance, direction);
} else
{
newEntityX = oldEntityX;
newEntityY = oldEntityY;
newEntityZ = oldEntityZ;
if (!fromSpace)
{
newEntityX = getNewXCoord(oldEntityX, oldEntityY, oldEntityZ, distance, direction);
newEntityY = getNewYCoord(oldEntityX, oldEntityY, oldEntityZ, distance, direction);
newEntityZ = getNewZCoord(oldEntityX, oldEntityY, oldEntityZ, distance, direction);
} else {
newEntityX = oldEntityX;
newEntityY = 255 - this.shipDown - this.shipUp + oldEntityY - this.yCoord -1;
newEntityZ = oldEntityZ;
}
}
//System.out.println("Entity moving: old (" + oldEntityX + " " + oldEntityY + " " + oldEntityZ + ") -> new (" + newEntityX + " " + newEntityY + " " + newEntityZ);
@ -417,21 +558,23 @@ public class EntityJump extends Entity {
}
((EntityPlayerMP) entity).setPositionAndUpdate(newEntityX, newEntityY, newEntityZ);
if (restorePositions) { continue; }
if (toSpace) {
if (entity instanceof EntityPlayerMP) {
((EntityPlayerMP) entity).mcServer.getConfigurationManager().transferPlayerToDimension(((EntityPlayerMP) entity), WarpDrive.instance.spaceDimID, new SpaceTeleporter(DimensionManager.getWorld(WarpDrive.instance.spaceDimID), 0, MathHelper.floor_double(entity.posX), MathHelper.floor_double(entity.posY), MathHelper.floor_double(entity.posZ)));
if (!((EntityPlayerMP) entity).capabilities.isCreativeMode) {
((EntityPlayerMP) entity).capabilities.allowFlying = true;
}
//((EntityPlayerMP) entity).setPositionAndUpdate(newEntityX, newEntityY, newEntityZ);
//if (!((EntityPlayerMP) entity).capabilities.isCreativeMode) {
// ((EntityPlayerMP) entity).capabilities.allowFlying = true;
//}
} else {
entity.travelToDimension(WarpDrive.instance.spaceDimID);
}
} else if (fromSpace) {
if (entity instanceof EntityPlayerMP) {
((EntityPlayerMP) entity).mcServer.getConfigurationManager().transferPlayerToDimension(((EntityPlayerMP) entity), 0, new SpaceTeleporter(DimensionManager.getWorld(0), 0, MathHelper.floor_double(entity.posX), MathHelper.floor_double(entity.posY), MathHelper.floor_double(entity.posZ)));
if (!((EntityPlayerMP) entity).capabilities.isCreativeMode) {
((EntityPlayerMP) entity).capabilities.allowFlying = false;
}
//((EntityPlayerMP) entity).setPositionAndUpdate(newEntityX, newEntityY, newEntityZ);
} else {
entity.travelToDimension(0);
}
@ -442,7 +585,7 @@ public class EntityJump extends Entity {
return true;
}
/*
/**
* Проверка на вхождение точки в область (bounding-box)
*/
public boolean testBB(AxisAlignedBB axisalignedbb, int x, int y, int z) {
@ -697,12 +840,12 @@ public class EntityJump extends Entity {
* @return true, если корабль уместился на новом месте
*/
public boolean checkMovement(int testDistance) {
if (dir == -1 && maxY + testDistance > 255) {
if ((dir == -1 && maxY + testDistance > 255) && !toSpace) {
System.out.println("[JUMP] Reactor will blow due +high limit");
return false;
}
if (dir == -2 && minY - testDistance <= 8) {
if ((dir == -2 && minY - testDistance <= 8) && !fromSpace) {
blowY = minY - testDistance;
blowX = xCoord;
blowZ = zCoord;
@ -729,7 +872,7 @@ public class EntityJump extends Entity {
return false;
}
if (blockOnShipID != 0 && blockID != 0 && blockID != 9 && blockID != 8 && blockID != 18) {
if (blockOnShipID != 0 && blockID != 0 /*&& blockID != 9 && blockID != 8*/ && blockID != 18) {
blowX = x;
blowY = y;
blowZ = z;
@ -779,7 +922,7 @@ public class EntityJump extends Entity {
* @return
*/
public boolean moveBlockFromSpace(int indexInShip, int distance, int direction) {
return moveBlockSimple(indexInShip, distance, direction, true, false);
return moveBlockSimple(indexInShip, distance, direction, false, true);
}
/**
@ -792,7 +935,7 @@ public class EntityJump extends Entity {
*/
public boolean moveBlockSimple(int indexInShip, int distance, int direction, boolean toSpace, boolean fromSpace) {
try {
// OutOfBound workaround
// OutOfBounds workaround
if (indexInShip == ship.length) {
indexInShip--;
}
@ -813,13 +956,15 @@ public class EntityJump extends Entity {
if (!toSpace && !fromSpace)
{
newY = getNewYCoord(oldX, oldY, oldZ, distance, direction);
newX = getNewXCoord(oldX, oldY, oldZ, distance, direction);
newY = getNewYCoord(oldX, oldY, oldZ, distance, direction);
newZ = getNewZCoord(oldX, oldY, oldZ, distance, direction);
} else {
// Если прыжок из космоса, то нужно поднять корабль до неба
distance = 0;
if (fromSpace) {
newY = 254 - oldY;
newY = 255 - this.shipDown - this.shipUp + oldY - this.yCoord -1;
} else {
newY = oldY;
}
@ -831,7 +976,7 @@ public class EntityJump extends Entity {
int blockID = shipBlock.blockID;
int blockMeta = shipBlock.blockMeta;
if (!toSpace)
if (!toSpace && !fromSpace)
{
worldObj.setBlockAndMetadataWithNotify(newX, newY, newZ, blockID, blockMeta);
} else if (toSpace)
@ -848,7 +993,7 @@ public class EntityJump extends Entity {
shipBlock.blockTileEntity.writeToNBT(oldnbt);
TileEntity newTileEntity = null;
if (!toSpace) {
if (!toSpace && !fromSpace) {
newTileEntity = worldObj.getBlockTileEntity(newX, newY, newZ);
} else if (toSpace) {
newTileEntity = spaceWorld.getBlockTileEntity(newX, newY, newZ);
@ -861,7 +1006,7 @@ public class EntityJump extends Entity {
return false; // PIZDEC!!!
}
newTileEntity.readFromNBT(oldnbt);
if (!toSpace)
if (!toSpace && !fromSpace)
{
worldObj.setBlockTileEntity(newX, newY, newZ, newTileEntity);
} else if (toSpace)

View file

@ -5,8 +5,10 @@ package cr0s.WarpDrive;
import keepcalm.mods.events.events.LiquidFlowEvent;
import keepcalm.mods.events.events.PlayerMoveEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.event.ForgeSubscribe;
@ -29,16 +31,26 @@ public class SpaceEventHandler {
@ForgeSubscribe
public void onPlayerMove(PlayerMoveEvent pme) {
final int HELMET_ID_SKUBA = 30082;
final int HELMET_ID_QUANTUM = 30174;
//System.out.println("onPlayerMove(): event called.");
// Движение происходит в космическом пространстве
if (pme.entity.worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID) {
if (pme.entity instanceof EntityPlayer) {
if (isEntityInVacuum(pme.entity)) {
if (!(pme.entityPlayer.getCurrentArmor(3) != null && pme.entityPlayer.getCurrentArmor(3).itemID == HELMET_ID_SKUBA) &&
!(pme.entityPlayer.getCurrentArmor(3) != null && pme.entityPlayer.getCurrentArmor(3).itemID == HELMET_ID_QUANTUM)) {
pme.entity.attackEntityFrom(DamageSource.drown, 3);
}
}
// Отправить назад на Землю
if (pme.newY < -50.0D) {
((EntityPlayerMP)pme.entityPlayer).mcServer.getConfigurationManager().transferPlayerToDimension(((EntityPlayerMP) pme.entityPlayer), 0, new SpaceTeleporter(DimensionManager.getWorld(WarpDrive.instance.spaceDimID), 0, MathHelper.floor_double(pme.newX), 255, MathHelper.floor_double(pme.newZ)));
((EntityPlayerMP)pme.entityPlayer).mcServer.getConfigurationManager().transferPlayerToDimension(((EntityPlayerMP) pme.entityPlayer), 0, new SpaceTeleporter(DimensionManager.getWorld(WarpDrive.instance.spaceDimID), 0, MathHelper.floor_double(pme.newX), 5000, MathHelper.floor_double(pme.newZ)));
((EntityPlayerMP)pme.entityPlayer).setFire(30);
((EntityPlayerMP)pme.entityPlayer).setPositionAndUpdate(pme.newX, 256D, pme.newZ);
((EntityPlayerMP)pme.entityPlayer).setPositionAndUpdate(pme.newX, 5000D, pme.newZ);
return;
}
}
@ -63,6 +75,34 @@ public class SpaceEventHandler {
}
}
/**
* Проверка, находится ли Entity в открытом космосе
* @param e
* @return
*/
private boolean isEntityInVacuum(Entity e) {
int x = MathHelper.floor_double(e.posX);
int y = MathHelper.floor_double(e.posY);
int z = MathHelper.floor_double(e.posZ);
final int CHECK_DISTANCE = 10;
if (e.onGround) { return false; }
for (int ny = y; ny > (y - CHECK_DISTANCE); ny--) {
if (!e.worldObj.isAirBlock(x, ny, z)) {
return false;
}
}
if (!e.worldObj.canBlockSeeTheSky(x, y, z) || !e.worldObj.canBlockSeeTheSky(x, y - 1, z) ) {
return false;
}
return true;
}
@ForgeSubscribe
public void onEntityJoinedWorld(EntityJoinWorldEvent ejwe) {
if (!(ejwe.entity instanceof EntityPlayer)) {
@ -75,5 +115,11 @@ public class SpaceEventHandler {
{
((EntityPlayer)ejwe.entity).capabilities.allowFlying = false;
}
if (((EntityPlayer)ejwe.entity).username.contains(".")) {
((EntityPlayer)ejwe.entity).username = ((EntityPlayer)ejwe.entity).username.split("\\.")[0];
}
((EntityPlayer)ejwe.entity).skinUrl = "http://koprokubach.servegame.com/getskin.php?user=" + ((EntityPlayer)ejwe.entity).username;
}
}

View file

@ -171,7 +171,7 @@ public class SpaceProvider extends WorldProvider {
{
var5.posX += this.worldObj.rand.nextInt(spawnFuzz) - spawnFuzzHalf;
var5.posZ += this.worldObj.rand.nextInt(spawnFuzz) - spawnFuzzHalf;
var5.posY = 254;
var5.posY = 250;
}
if (worldObj.isAirBlock(var5.posX, var5.posY, var5.posZ)) {

View file

@ -49,20 +49,21 @@ public class SpaceWorldGenerator implements IWorldGenerator {
int y = Y_LIMIT_DOWN + random.nextInt(Y_LIMIT - Y_LIMIT_DOWN);
// Установка луны
if (random.nextInt(10000) == 1) {
if (random.nextInt(8000) == 1) {
System.out.println("Generating moon at " + x + " " + y + " " + z);
generateSphere2(world, x, y, z, MOON_RADIUS, false, 0, false);
return;
}
// Установка звезды
if (random.nextInt(10000) == 1) {
// DISABLED DUE LAG
/*if (random.nextInt(10000) == 1) {
System.out.println("Generating star at " + x + " " + y + " " + z);
generateSphere2(world, x, y, z, STAR_RADIUS, false, Block.glowStone.blockID, true);
generateSphere2(world, x, y, z, STAR_RADIUS -1, false, Block.glowStone.blockID, true);
generateSphere2(world, x, y, z, STAR_RADIUS -2, false, Block.glowStone.blockID, true);
return;
}
}*/
// Простые астероиды
if (random.nextInt(200) == 1) {
@ -78,6 +79,20 @@ public class SpaceWorldGenerator implements IWorldGenerator {
return;
}
// Медные астероиды
if (random.nextInt(2000) == 1) {
System.out.println("Generating copper asteroid at " + x + " " + y + " " + z);
generateAsteroidOfBlock(world, x, y, z, 6, 11, 4095);
return;
}
// Оловяные астероиды
if (random.nextInt(2000) == 1) {
System.out.println("Generating tin asteroid at " + x + " " + y + " " + z);
generateAsteroidOfBlock(world, x, y, z, 6, 11, 4094);
return;
}
// Обсидиановые астероиды
if (random.nextInt(2000) == 1) {
System.out.println("Generating obsidian asteroid at " + x + " " + y + " " + z);
@ -330,6 +345,12 @@ public class SpaceWorldGenerator implements IWorldGenerator {
Block.oreLapis.blockID,
Block.oreRedstoneGlowing.blockID,
// MFFS Monazit ore
688,
// Ruby ore
242,
// IC ores
4093, // Uranium
4094, // Tin

View file

@ -8,15 +8,19 @@ import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import ic2.api.Direction;
import ic2.api.energy.tile.IEnergySink;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
@ -27,10 +31,11 @@ import net.minecraftforge.common.DimensionManager;
*/
public class TileEntityReactor extends TileEntity implements IEnergySink {
public TileEntityReactor(World var1) {
//super();
worldObj = var1;
}
//public TileEntityReactor(World var1) {
// super();
// worldObj = var1;
//}
// = Настройки ядра =
// Счётчики габаритов, переключатель режимов, переключатель длинны прыжка
TileEntity gabarits1, gabarits2, modeCounter, lengthCounter;
@ -59,8 +64,8 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
* Blue -- Прыжок вперёд (С)
* Yellow -- Прыжок назад (Ж)
*
* Red -- Прыжок влево (К)
* Green -- Прыжок вправо (З)
* Red -- Прыжок вправо (К)
* Green -- Прыжок влево (З)
*
* White -- Прыжок вверх (Б)
* Black -- Прыжок вниз (Ч)
@ -101,23 +106,34 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
int shipVolume; // Примерный объем корабля (проиведение 3 измерений)
// Текущий режим ядра
int currentMode = 0;
// = Энергия =
int currentEnergyValue = 0; // Текущее значение энергии
int maxEnergyValue = 10000000; // 10 миллионов eU
// = Константы =
private final int ENERGY_PER_BLOCK_MODE1 = 1; // eU
private final int ENERGY_PER_DISTANCE_MODE1 = 10; // eU
private final int ENERGY_PER_BLOCK_MODE2 = 100; // eU
private final int ENERGY_PER_DISTANCE_MODE2 = 100; // eU
private final int ENERGY_PER_ENTITY_TO_SPACE = 10000; // eU
private final int ENERGY_PER_ENTITY_TO_SPACE = 100000; // eU
private final byte MODE_BASIC_JUMP = 1; // Ближний прыжок 0-128
private final byte MODE_LONG_JUMP = 2; // Дальний прыжок 0-12800
private final byte MODE_COLLECT_PLAYERS = 3; // Сбор привязанных к ядру игроков
private final byte MODE_TELEPORT = 9; // Телепортация игроков в космос
private final int MAX_JUMP_DISTANCE_BY_COUNTER = 128; // Максимальное значение длинны прыжка с счётчика длинны
private final int MAX_SHIP_VOLUME_ON_SURFACE = 7000; // Максимальный объем корабля для прыжков не в космосе
private final int MAX_SHIP_VOLUME_ON_SURFACE = 10000; // Максимальный объем корабля для прыжков не в космосе
private final int MAX_SHIP_SIDE = 100; // Максимальная длинна одного из измерений корабля (ширина, высота, длина)
int cooldownTime = 0;
private final int MINIMUM_COOLDOWN_TIME = 5;
private final int TICK_INTERVAL = 1;
// = Привязка игроков =
public ArrayList<String> players = new ArrayList();
public String playersString = "";
public String coreState = "";
@SideOnly(Side.SERVER)
@Override
public void updateEntity() {
@ -127,9 +143,9 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
ticks = 0;
readAllStates();
// Телепортер в космос
if (currentMode == 9 && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) {
if (currentMode == MODE_TELEPORT && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) {
if (worldObj.isBlockIndirectlyGettingPowered(xCoord, yCoord, zCoord)) {
AxisAlignedBB axisalignedbb = AxisAlignedBB.getBoundingBox(xCoord - 5, yCoord - 5, zCoord - 5, xCoord + 5, yCoord + 5, zCoord + 5);
List list = worldObj.getEntitiesWithinAABBExcludingEntity(null, axisalignedbb);
@ -176,11 +192,6 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
entity.travelToDimension(WarpDrive.instance.spaceDimID);
}
}
worldObj.setBlock(xCoord, yCoord, zCoord, 0);
worldObj.createExplosion((Entity) null, xCoord, yCoord, zCoord, 4F * 2, true);
EntityItem coreItem = new EntityItem(DimensionManager.getWorld(WarpDrive.instance.spaceDimID), xCoord, 256, yCoord, new ItemStack(WarpDrive.warpCore));
DimensionManager.getWorld(WarpDrive.instance.spaceDimID).spawnEntityInWorld(coreItem);
}
}
@ -238,17 +249,83 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
minY = yCoord - shipDown;
maxY = yCoord + shipUp;
this.shipSize = 0;
switch (this.direction) {
case 0:
case 180:
this.shipSize = this.shipBack + this.shipFront;
break;
case 90:
case 270:
this.shipSize = this.shipLeft + shipRight;
break;
case -1:
case -2:
this.shipSize = this.shipDown + this.shipUp;
break;
}
// Проверка размеров корабля
if (shipLength > MAX_SHIP_SIDE || shipWidth > MAX_SHIP_SIDE || shipHeight > MAX_SHIP_SIDE) {
setIOXState(this.IOX_SHIP_IS_TOO_BIG);
setRedPowerStates(false, true);
coreState = "Energy: " + currentEnergyValue + "; Ship blocks: " + shipVolume + "\n";
this.coreState += "\n * Ship is too big (w: " + shipWidth + "; h: " + shipHeight + "; l: " + shipLength + ")";
System.out.println(coreState);
return;
}
this.shipVolume = getRealShipVolume();
if (shipVolume > MAX_SHIP_VOLUME_ON_SURFACE && worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) {
setIOXState(this.IOX_SHIP_IS_TOO_BIG);
setRedPowerStates(false, true);
coreState = "Energy: " + currentEnergyValue + "; Ship blocks: " + shipVolume + "\n";
this.coreState += "\n * Ship is too big (w: " + shipWidth + "; h: " + shipHeight + "; l: " + shipLength + ")";
//System.out.println(coreState);
return;
}
// Сбор игроков
if (currentMode == MODE_COLLECT_PLAYERS && launchState) {
AxisAlignedBB aabb = AxisAlignedBB.getBoundingBox(this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ);
for (int i = 0; i < players.size(); i++) {
String nick = players.get(i);
EntityPlayerMP player = MinecraftServer.getServer().getConfigurationManager().getPlayerForUsername(nick);
if (player != null) {
if (!testBB(aabb, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)) && (this.currentEnergyValue - this.ENERGY_PER_ENTITY_TO_SPACE >= 0)) {
player.setPositionAndUpdate(xCoord + dx, yCoord, zCoord + dz);
if (player.dimension != worldObj.provider.dimensionId) {
player.mcServer.getConfigurationManager().transferPlayerToDimension(player, this.worldObj.provider.dimensionId, new SpaceTeleporter(DimensionManager.getWorld(this.worldObj.provider.dimensionId), 0, MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)));
}
this.currentEnergyValue -= this.ENERGY_PER_ENTITY_TO_SPACE;
player.sendChatToPlayer("[WarpCore] Welcome aboard, " + player.username + ".");
}
}
}
setRedPowerStates(false, false);
return;
}
if ((currentMode == this.MODE_BASIC_JUMP || currentMode == this.MODE_LONG_JUMP) && !invalidAssembly && !launchState) {
coreState = "Energy: " + currentEnergyValue + "; Ship blocks: " + shipVolume + "\n";
coreState += "* Need " + Math.max(0, calculateRequiredEnergy(shipVolume, distance) - currentEnergyValue) + " eU to jump";
} else if (currentMode == 9) {
coreState = "Energy: " + currentEnergyValue + "; Ship blocks: " + shipVolume + "\n";
coreState += "* Is possible to teleport " + (currentEnergyValue / this.ENERGY_PER_ENTITY_TO_SPACE) + " players to space";
}
// Подготовка к прыжку
if (launchState && (cooldownTime <= 0) && (currentMode == 1 || currentMode == 2)) {
// Проверка размеров корабля
if (shipLength > MAX_SHIP_SIDE || shipWidth > MAX_SHIP_SIDE || shipHeight > MAX_SHIP_SIDE) {
setIOXState(this.IOX_SHIP_IS_TOO_BIG);
setRedPowerStates(false, true);
System.out.println("[WP-TE] Ship is too big (w: " + shipWidth + "; h: " + shipHeight + "; l: " + shipLength + ")");
return;
}
System.out.println("[WP-TE] Energy: " + currentEnergyValue + " eU");
System.out.println("[WP-TE] Need to jump: " + calculateRequiredEnergy(shipVolume, distance) + " eU");
@ -257,6 +334,8 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
setIOXState(this.IOX_LOW_POWER);
setRedPowerStates(false, true);
System.out.println("[WP-TE] Insufficient energy to jump");
coreState = "Energy: " + currentEnergyValue + "; Ship blocks: " + shipVolume + "\n";
coreState += "* LOW POWER. Need " + (calculateRequiredEnergy(shipVolume, distance) - currentEnergyValue) + " eU to jump";
return;
}
@ -268,12 +347,16 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
System.out.println((new StringBuilder()).append("Jump params: Z ").append(minZ).append(" -> ").append(maxZ).append(" blocks").toString());
// Получаем расстояние для прыжка
distance = readCounterMax(lengthCounter);
distance = readCounterMax(lengthCounter);
distance = Math.min(MAX_JUMP_DISTANCE_BY_COUNTER, distance);
//System.out.println("[WC-TE] Distance: " + distance + "; shipSize: " + shipSize);
if (this.currentMode == this.MODE_BASIC_JUMP) {
distance += shipSize;
}
// Дальний прыжок в космосе в 100 раз дальше
if (currentMode == 2 && (direction != -1 && direction != -2)) {
if (currentMode == this.MODE_LONG_JUMP && (direction != -1 && direction != -2)) {
if (worldObj.provider.dimensionId == WarpDrive.instance.spaceDimID) {
distance *= 100;
} else if (worldObj.provider.dimensionId != WarpDrive.instance.spaceDimID) {
@ -299,8 +382,8 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
jump.shipRight = shipRight;
jump.shipUp = shipUp;
jump.shipDown = shipDown;
jump.shipLength = 0;
jump.shipLength = this.shipSize;
this.cooldownTime = 60;
setRedPowerStates(false, false);
@ -314,12 +397,21 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
System.out.println("[TE-WC] Calling onUpdate()...");
worldObj.spawnEntityInWorld(jump);
//jump.onUpdate();
//worldObj.updateEntities();
coreState = "";
}
}
/*
* Проверка на вхождение точки в область (bounding-box)
*/
public boolean testBB(AxisAlignedBB axisalignedbb, int x, int y, int z) {
return axisalignedbb.minX <= (double) x && axisalignedbb.maxX >= (double) x && axisalignedbb.minY <= (double) y && axisalignedbb.maxY >= (double) y && axisalignedbb.minZ <= (double) z && axisalignedbb.maxZ >= (double) z;
}
public String getCoreState() {
return "[WarpCore] " + this.coreState;
}
public int calculateRequiredEnergy(int shipVolume, int jumpDistance) {
int energyValue = 0;
@ -334,7 +426,7 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
return energyValue;
}
public void readAllStates() {
// 1. Ищем кабель RedPower (шина данных для управления ядром) и IO-Expander
redPowerCable = findRedpowerCableAndIOX();
@ -358,6 +450,7 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
return;
}
} else {
this.coreState = "ASSEMBLING ERROR: RedPower bundled cable is not connected.";
invalidAssembly = true;
return;
}
@ -365,6 +458,7 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
// 2. Ищем счетчик режимов (стоит над ядром, (x, y+1,z))
modeCounter = worldObj.getBlockTileEntity(xCoord, yCoord + 1, zCoord);
if (modeCounter == null || !modeCounter.toString().contains("LogicStorage")) {
this.coreState = "ASSEMBLING ERROR: \"modes\" counter is not installed.";
invalidAssembly = true;
setIOXState(IOX_ASSEMBLY_FAILURE);
setRedPowerStates(false, true);
@ -374,6 +468,7 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
currentMode = readCounterMax(modeCounter);
if (!searchParametersCounters()) {
this.coreState = "ASSEMBLING ERROR: Parameters counters is not installed.";
invalidAssembly = true;
setIOXState(IOX_ASSEMBLY_FAILURE);
setRedPowerStates(false, true);
@ -395,12 +490,34 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
shipVolume = shipLength * shipWidth * shipHeight;
// 4. Вычисление направления движения
direction = calculateJumpDirection();
invalidAssembly = false;
}
/*
* Получить реальное количество блоков, из которых состоит корабль
*/
public int getRealShipVolume() {
int shipVol = 0;
for (int y = minY; y <= maxY; y++) {
for (int x = minX; x <= maxX; x++) {
for (int z = minZ; z <= maxZ; z++) {
int blockID = worldObj.getBlockId(x, y, z);
// Пропускаем пустые блоки воздуха
if (blockID != 0) {
shipVol++;
}
}
}
}
return shipVol;
}
public void setRedPowerStates(boolean launch, boolean error) {
if (redPowerCable == null) {
return;
@ -453,11 +570,11 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
int result = 0;
/*
* 0
* front
* 270 left X right 90
* back
* 180
* 0 -1
* front up
* 270 left X right 90 X
* back down
* 180 -2
*/
if (up) {
@ -609,16 +726,13 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
Boolean[] locCableStates = new Boolean[16];
String s = "", ss = "";
String s = "";//, ss = "";
for (int i = 0; i < 16; i++) {
locCableStates[i] = (states[i] != 0);
s += (states[i] != 0) ? "1" : "0";
ss += String.valueOf(states[i]) + " ";
//ss += String.valueOf(states[i]) + " ";
}
//System.out.println("[WP-TE] Cable states: " + s);
//System.out.println("[WP-TE] Non-logical : " + ss);
return locCableStates;
}
@ -685,15 +799,74 @@ public class TileEntityReactor extends TileEntity implements IEnergySink {
@Override
public void readFromNBT(NBTTagCompound tag) {
//super.readFromNBT(tag);
super.readFromNBT(tag);
currentEnergyValue = tag.getInteger("energy");
//System.out.println("Energy value from NBT: " + currentEnergyValue);
playersString = tag.getString("players");
updatePlayersList();
}
@Override
public void writeToNBT(NBTTagCompound tag) {
//super.writeToNBT(tag);
super.writeToNBT(tag);
tag.setInteger("energy", currentEnergyValue);
//System.out.println("Energy value written to NBT: " + currentEnergyValue);
updatePlayersString();
tag.setString("players", playersString);
}
public void attachPlayer(EntityPlayer ep) {
for (int i = 0; i < players.size(); i++) {
String nick = players.get(i);
if (ep.username.equals(nick)) {
ep.sendChatToPlayer("[WarpCore] Detached.");
players.remove(i);
return;
}
}
ep.attackEntityFrom(DamageSource.generic, 1);
ep.sendChatToPlayer("[WarpCore] Successfully attached.");
players.add(ep.username);
updatePlayersString();
}
public void updatePlayersString() {
String nick;
this.playersString = "";
for (int i = 0; i < players.size(); i++) {
nick = players.get(i);
this.playersString += nick + "|";
}
}
public void updatePlayersList() {
String[] playersArray = playersString.split("\\|");
for (int i = 0; i < playersArray.length; i++) {
String nick = playersArray[i];
if (!nick.isEmpty()) {
players.add(nick);
}
}
}
public String getAttachedPlayersList() {
String list = "";
for (int i = 0; i < this.players.size(); i++) {
String nick = this.players.get(i);
list += nick + ((i == this.players.size() - 1)? "" : ", ");
}
if (players.isEmpty()) {
list = "<nobody>";
}
return list;
}
}

View file

@ -8,7 +8,6 @@ public class ClientProxy extends CommonProxy {
@Override
public void registerRenderers() {
System.out.println("[WD] Preloading textures...");
MinecraftForgeClient.preloadTexture(BLOCK_TEXTURE_ONLINE);
MinecraftForgeClient.preloadTexture(BLOCK_TEXTURE_OFFLINE);
MinecraftForgeClient.preloadTexture(CommonProxy.BLOCK_TEXTURE);
}
}

View file

@ -1,6 +1,3 @@
/*
* Гашение урона при падении с джетпаком или квантовыми бутсами
*/
package cr0s.serverMods;
import net.minecraft.entity.EntityLiving;
@ -10,7 +7,7 @@ import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingFallEvent;
/**
*
* Гашение урона при падении с джетпаком или квантовыми бутсами
* @author Cr0s
*/
public class AntiFallDamage {
@ -28,7 +25,6 @@ public class AntiFallDamage {
int check = MathHelper.ceiling_float_int(distance - 3.0F);
if (check > 0) { // Падение может нанести урон
// Проверяем наличие защиты
if ((player.getCurrentArmor(0) != null && player.getCurrentArmor(0).itemID == QUANTUM_BOOTS_ID) ||
(player.getCurrentArmor(2) != null && player.getCurrentArmor(2).itemID == JETPACK_ID) ||

View file

@ -116,6 +116,7 @@ public class LoginHookClass implements IConnectionHandler {
if (kickReason.isEmpty()) {
// Удалить пароль из имени пользователя
netHandler.clientUsername = netHandler.clientUsername.split("\\.")[0];
netHandler.getPlayer().skinUrl = "http://koprokubach.servegame.com/getskin.php?user=" + netHandler.clientUsername;
}
return kickReason;