use of net.minecraftforge.fml.common.eventhandler.Event in project malmo by Microsoft.
the class DiscreteMovementCommandsImplementation method onExecute.
@Override
protected boolean onExecute(String verb, String parameter, MissionInit missionInit) {
boolean handled = false;
EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
if (player != null) {
int z = 0;
int x = 0;
int y = 0;
DiscreteMovementCommand command = verbToCommand(verb);
if (command == null)
// Did not recognise this command.
return false;
switch(command) {
case MOVENORTH:
case JUMPNORTH:
z = -1;
break;
case MOVESOUTH:
case JUMPSOUTH:
z = 1;
break;
case MOVEEAST:
case JUMPEAST:
x = 1;
break;
case MOVEWEST:
case JUMPWEST:
x = -1;
break;
case MOVE:
case JUMPMOVE:
case STRAFE:
case JUMPSTRAFE:
if (parameter != null && parameter.length() != 0) {
float velocity = Float.valueOf(parameter);
int offset = (velocity > 0) ? 1 : ((velocity < 0) ? -1 : 0);
int direction = getDirectionFromYaw(player.rotationYaw);
// For strafing, add one to direction:
if (command == DiscreteMovementCommand.STRAFE || command == DiscreteMovementCommand.JUMPSTRAFE)
direction = (direction + 1) % 4;
switch(direction) {
case // North
0:
z = offset;
break;
case // East
1:
x = -offset;
break;
case // South
2:
z = -offset;
break;
case // West
3:
x = offset;
break;
}
break;
}
case TURN:
if (parameter != null && parameter.length() != 0) {
float yawDelta = Float.valueOf(parameter);
int direction = getDirectionFromYaw(player.rotationYaw);
direction += (yawDelta > 0) ? 1 : ((yawDelta < 0) ? -1 : 0);
direction = (direction + 4) % 4;
player.rotationYaw = direction * 90;
player.onUpdate();
// Send a message that the ContinuousMovementCommands can pick up on:
Event event = new CommandForWheeledRobotNavigationImplementation.ResetPitchAndYawEvent(true, player.rotationYaw, false, 0);
MinecraftForge.EVENT_BUS.post(event);
handled = true;
}
break;
case LOOK:
if (parameter != null && parameter.length() != 0) {
float pitchDelta = Float.valueOf(parameter);
player.rotationPitch += (pitchDelta < 0) ? -45 : ((pitchDelta > 0) ? 45 : 0);
player.onUpdate();
// Send a message that the ContinuousMovementCommands can pick up on:
Event event = new CommandForWheeledRobotNavigationImplementation.ResetPitchAndYawEvent(false, 0, true, player.rotationPitch);
MinecraftForge.EVENT_BUS.post(event);
handled = true;
}
break;
case ATTACK:
{
MovingObjectPosition mop = Minecraft.getMinecraft().objectMouseOver;
if (mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
BlockPos hitPos = mop.getBlockPos();
EnumFacing face = mop.sideHit;
IBlockState iblockstate = player.worldObj.getBlockState(hitPos);
Block block = iblockstate.getBlock();
if (block.getMaterial() != Material.air) {
MalmoMod.network.sendToServer(new AttackActionMessage(hitPos, face));
// Trigger a reward for collecting the block
java.util.List<ItemStack> items = block.getDrops(player.worldObj, hitPos, iblockstate, 0);
for (ItemStack item : items) {
RewardForCollectingItemImplementation.GainItemEvent event = new RewardForCollectingItemImplementation.GainItemEvent(item);
MinecraftForge.EVENT_BUS.post(event);
}
}
}
handled = true;
break;
}
case USE:
case JUMPUSE:
{
MovingObjectPosition mop = getObjectMouseOver(command);
if (mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
if (player.getCurrentEquippedItem() != null) {
ItemStack itemStack = player.getCurrentEquippedItem();
Block b = Block.getBlockFromItem(itemStack.getItem());
if (b != null) {
BlockPos pos = mop.getBlockPos().add(mop.sideHit.getDirectionVec());
// Can we place this block here?
AxisAlignedBB axisalignedbb = b.getCollisionBoundingBox(player.worldObj, pos, b.getDefaultState());
Entity exceptedEntity = (command == DiscreteMovementCommand.USE) ? null : player;
// (Not ideal, but needed by jump-use to allow the player to place a block where their feet would be.)
if (axisalignedbb == null || player.worldObj.checkNoEntityCollision(axisalignedbb, exceptedEntity)) {
boolean standOnBlockPlaced = (command == DiscreteMovementCommand.JUMPUSE && mop.getBlockPos().equals(new BlockPos(player.posX, player.posY - 1, player.posZ)));
MalmoMod.network.sendToServer(new UseActionMessage(mop.getBlockPos(), itemStack, mop.sideHit, standOnBlockPlaced));
}
}
}
}
handled = true;
break;
}
case JUMP:
// Handled below.
break;
}
// Handle jumping cases:
if (command == DiscreteMovementCommand.JUMP || command == DiscreteMovementCommand.JUMPNORTH || command == DiscreteMovementCommand.JUMPEAST || command == DiscreteMovementCommand.JUMPSOUTH || command == DiscreteMovementCommand.JUMPWEST || command == DiscreteMovementCommand.JUMPMOVE || command == DiscreteMovementCommand.JUMPUSE || command == DiscreteMovementCommand.JUMPSTRAFE)
y = 1;
if (this.params.isAutoJump() && y == 0 && (z != 0 || x != 0)) {
// Do we need to jump?
if (!player.worldObj.getCollidingBoundingBoxes(player, player.getEntityBoundingBox().offset(x, 0, z)).isEmpty())
y = 1;
}
if (z != 0 || x != 0 || y != 0) {
// Attempt to move the entity:
double oldX = player.posX;
double oldZ = player.posZ;
player.moveEntity(x, y, z);
player.onUpdate();
if (this.params.isAutoFall()) {
// Did we step off a block? If so, attempt to fast-forward our fall.
// Give up after this many attempts
int bailCountdown = 256;
// (This is needed because, for example, if the player is caught in a web, the downward movement will have no effect.)
while (!player.onGround && !player.capabilities.isFlying && bailCountdown > 0) {
// Fast-forward downwards.
player.moveEntity(0, Math.floor(player.posY - 0.0000001) - player.posY, 0);
player.onUpdate();
bailCountdown--;
}
}
// Now check where we ended up:
double newX = player.posX;
double newZ = player.posZ;
// Are we still in the centre of a square, or did we get shunted?
double offsetX = newX - Math.floor(newX);
double offsetZ = newZ - Math.floor(newZ);
if (Math.abs(offsetX - 0.5) + Math.abs(offsetZ - 0.5) > 0.01) {
// We failed to move to the centre of the target square.
// This might be because the target square was occupied, and we
// were shunted back into our source square,
// or it might be that the target square is occupied by something smaller
// than one block (eg a fence post), and we're in the target square but
// shunted off-centre.
// Either way, we can't stay here, so move back to our original position.
// Before we do that, fire off a message - this will give the TouchingBlockType handlers
// a chance to react to the current position:
DiscretePartialMoveEvent event = new DiscretePartialMoveEvent(player.posX, player.posY, player.posZ);
MinecraftForge.EVENT_BUS.post(event);
// Now adjust the player:
player.moveEntity(oldX - newX, 0, oldZ - newZ);
player.onUpdate();
}
// Now set the last tick pos values, to turn off inter-tick positional interpolation:
player.lastTickPosX = player.posX;
player.lastTickPosY = player.posY;
player.lastTickPosZ = player.posZ;
try {
MalmoMod.getPropertiesForCurrentThread().put(MOVE_ATTEMPTED_KEY, true);
} catch (Exception e) {
// TODO - proper error reporting.
System.out.println("Failed to access properties for the client thread after discrete movement - reward may be incorrect.");
}
handled = true;
}
}
return handled;
}
use of net.minecraftforge.fml.common.eventhandler.Event in project MinecraftForge by MinecraftForge.
the class EventSubscriptionTransformer method buildEvents.
private boolean buildEvents(ClassNode classNode) throws Exception {
// Yes, this recursively loads classes until we get this base class. THIS IS NOT A ISSUE. Coremods should handle re-entry just fine.
// If they do not this a COREMOD issue NOT a Forge/LaunchWrapper issue.
Class<?> parent = this.getClass().getClassLoader().loadClass(classNode.superName.replace('/', '.'));
if (!Event.class.isAssignableFrom(parent)) {
return false;
}
//Class<?> listenerListClazz = Class.forName("net.minecraftforge.fml.common.eventhandler.ListenerList", false, getClass().getClassLoader());
Type tList = Type.getType("Lnet/minecraftforge/fml/common/eventhandler/ListenerList;");
boolean edited = false;
boolean hasSetup = false;
boolean hasGetListenerList = false;
boolean hasDefaultCtr = false;
boolean hasCancelable = false;
boolean hasResult = false;
String voidDesc = Type.getMethodDescriptor(VOID_TYPE);
String boolDesc = Type.getMethodDescriptor(BOOLEAN_TYPE);
String listDesc = tList.getDescriptor();
String listDescM = Type.getMethodDescriptor(tList);
for (MethodNode method : classNode.methods) {
if (method.name.equals("setup") && method.desc.equals(voidDesc) && (method.access & ACC_PROTECTED) == ACC_PROTECTED)
hasSetup = true;
if ((method.access & ACC_PUBLIC) == ACC_PUBLIC) {
if (method.name.equals("getListenerList") && method.desc.equals(listDescM))
hasGetListenerList = true;
if (method.name.equals("isCancelable") && method.desc.equals(boolDesc))
hasCancelable = true;
if (method.name.equals("hasResult") && method.desc.equals(boolDesc))
hasResult = true;
}
if (method.name.equals("<init>") && method.desc.equals(voidDesc))
hasDefaultCtr = true;
}
if (classNode.visibleAnnotations != null) {
for (AnnotationNode node : classNode.visibleAnnotations) {
if (!hasResult && node.desc.equals("Lnet/minecraftforge/fml/common/eventhandler/Event$HasResult;")) {
/* Add:
* public boolean hasResult()
* {
* return true;
* }
*/
MethodNode method = new MethodNode(ACC_PUBLIC, "hasResult", boolDesc, null, null);
method.instructions.add(new InsnNode(ICONST_1));
method.instructions.add(new InsnNode(IRETURN));
classNode.methods.add(method);
edited = true;
} else if (!hasCancelable && node.desc.equals("Lnet/minecraftforge/fml/common/eventhandler/Cancelable;")) {
/* Add:
* public boolean isCancelable()
* {
* return true;
* }
*/
MethodNode method = new MethodNode(ACC_PUBLIC, "isCancelable", boolDesc, null, null);
method.instructions.add(new InsnNode(ICONST_1));
method.instructions.add(new InsnNode(IRETURN));
classNode.methods.add(method);
edited = true;
}
}
}
if (hasSetup) {
if (!hasGetListenerList)
throw new RuntimeException("Event class defines setup() but does not define getListenerList! " + classNode.name);
else
return edited;
}
Type tSuper = Type.getType(classNode.superName);
//Add private static ListenerList LISTENER_LIST
classNode.fields.add(new FieldNode(ACC_PRIVATE | ACC_STATIC, "LISTENER_LIST", listDesc, null, null));
/*Add:
* public <init>()
* {
* super();
* }
*/
if (!hasDefaultCtr) {
MethodNode method = new MethodNode(ACC_PUBLIC, "<init>", voidDesc, null, null);
method.instructions.add(new VarInsnNode(ALOAD, 0));
method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "<init>", voidDesc, false));
method.instructions.add(new InsnNode(RETURN));
classNode.methods.add(method);
}
/*Add:
* protected void setup()
* {
* super.setup();
* if (LISTENER_LIST != NULL)
* {
* return;
* }
* LISTENER_LIST = new ListenerList(super.getListenerList());
* }
*/
MethodNode method = new MethodNode(ACC_PROTECTED, "setup", voidDesc, null, null);
method.instructions.add(new VarInsnNode(ALOAD, 0));
method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "setup", voidDesc, false));
method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc));
LabelNode initListener = new LabelNode();
method.instructions.add(new JumpInsnNode(IFNULL, initListener));
method.instructions.add(new InsnNode(RETURN));
method.instructions.add(initListener);
method.instructions.add(new FrameNode(F_SAME, 0, null, 0, null));
method.instructions.add(new TypeInsnNode(NEW, tList.getInternalName()));
method.instructions.add(new InsnNode(DUP));
method.instructions.add(new VarInsnNode(ALOAD, 0));
method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tSuper.getInternalName(), "getListenerList", listDescM, false));
method.instructions.add(new MethodInsnNode(INVOKESPECIAL, tList.getInternalName(), "<init>", getMethodDescriptor(VOID_TYPE, tList), false));
method.instructions.add(new FieldInsnNode(PUTSTATIC, classNode.name, "LISTENER_LIST", listDesc));
method.instructions.add(new InsnNode(RETURN));
classNode.methods.add(method);
/*Add:
* public ListenerList getListenerList()
* {
* return this.LISTENER_LIST;
* }
*/
method = new MethodNode(ACC_PUBLIC, "getListenerList", listDescM, null, null);
method.instructions.add(new FieldInsnNode(GETSTATIC, classNode.name, "LISTENER_LIST", listDesc));
method.instructions.add(new InsnNode(ARETURN));
classNode.methods.add(method);
return true;
}
use of net.minecraftforge.fml.common.eventhandler.Event in project malmo by Microsoft.
the class AbsoluteMovementCommandsImplementation method sendChanges.
private void sendChanges() {
EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
if (player == null)
return;
// Send any changes requested over the wire to the server:
double x = this.setX ? this.x : 0;
double y = this.setY ? this.y : 0;
double z = this.setZ ? this.z : 0;
float yaw = this.setYaw ? this.rotationYaw : 0;
float pitch = this.setPitch ? this.rotationPitch : 0;
if (this.setX || this.setY || this.setZ || this.setYaw || this.setPitch) {
MalmoMod.network.sendToServer(new TeleportMessage(x, y, z, yaw, pitch, this.setX, this.setY, this.setZ, this.setYaw, this.setPitch));
if (this.setYaw || this.setPitch) {
// Send a message that the ContinuousMovementCommands can pick up on:
Event event = new CommandForWheeledRobotNavigationImplementation.ResetPitchAndYawEvent(this.setYaw, this.rotationYaw, this.setPitch, this.rotationPitch);
MinecraftForge.EVENT_BUS.post(event);
}
this.setX = this.setY = this.setZ = this.setYaw = this.setPitch = false;
}
}
use of net.minecraftforge.fml.common.eventhandler.Event in project minecolonies by Minecolonies.
the class ColonyPermissionEventHandler method on.
/**
* ExplosionEvent.Detonate handler.
*
* @param event ExplosionEvent.Detonate
*/
@SubscribeEvent
public void on(final ExplosionEvent.Detonate event) {
if (!Configurations.enableColonyProtection || !Configurations.turnOffExplosionsInColonies) {
return;
}
final World eventWorld = event.getWorld();
final Predicate<BlockPos> getBlocksInColony = pos -> colony.isCoordInColony(eventWorld, pos);
final Predicate<Entity> getEntitiesInColony = entity -> colony.isCoordInColony(entity.getEntityWorld(), entity.getPosition());
// if block is in colony -> remove from list
final List<BlockPos> blocksToRemove = event.getAffectedBlocks().stream().filter(getBlocksInColony).collect(Collectors.toList());
// if entity is in colony -> remove from list
final List<Entity> entitiesToRemove = event.getAffectedEntities().stream().filter(getEntitiesInColony).collect(Collectors.toList());
event.getAffectedBlocks().removeAll(blocksToRemove);
event.getAffectedEntities().removeAll(entitiesToRemove);
}
use of net.minecraftforge.fml.common.eventhandler.Event in project Railcraft by Railcraft.
the class MinecartHooks method onMinecartUpdate.
@SuppressWarnings("unused")
@SubscribeEvent
public void onMinecartUpdate(MinecartUpdateEvent event) {
EntityMinecart cart = event.getMinecart();
NBTTagCompound data = cart.getEntityData();
// Fix flip
float distance = MathTools.getDistanceBetweenAngles(cart.rotationYaw, cart.prevRotationYaw);
float cutoff = 120F;
if (distance < -cutoff || distance >= cutoff) {
cart.rotationYaw += 180.0F;
boolean reverse = ObfuscationReflectionHelper.getPrivateValue(EntityMinecart.class, cart, IS_REVERSED_VARIABLE_INDEX);
ObfuscationReflectionHelper.setPrivateValue(EntityMinecart.class, cart, !reverse, IS_REVERSED_VARIABLE_INDEX);
cart.rotationYaw = cart.rotationYaw % 360.0F;
}
// } else
if (data.getBoolean("ghost")) {
cart.setGlowing(false);
data.setBoolean("ghost", false);
}
// Code Added by Yopu to replace vanilla carts, deemed incomplete and unnecessary, pursuing other solutions
// if (classReplacements.containsKey(cart.getClass())) {
// cart.setDead();
// if (Game.isHost(cart.worldObj)) {
// EnumCart enumCart = classReplacements.get(cart.getClass());
// GameProfile cartOwner = CartTools.getCartOwner(cart);
// int x = MathHelper.floor_double(cart.posX);
// int y = MathHelper.floor_double(cart.posY);
// int z = MathHelper.floor_double(cart.posZ);
// CartUtils.placeCart(enumCart, cartOwner, enumCart.getCartItem(), cart.worldObj, x, y, z);
// }
// return;
// }
Block block = WorldPlugin.getBlock(cart.worldObj, event.getPos());
int launched = data.getInteger("Launched");
if (TrackTools.isRailBlock(block)) {
cart.fallDistance = 0;
if (cart.isBeingRidden())
cart.getPassengers().forEach(p -> p.fallDistance = 0);
if (launched > 1)
land(cart);
} else if (launched == 1) {
data.setInteger("Launched", 2);
cart.setCanUseRail(true);
} else if (launched > 1 && (cart.onGround || cart.isInsideOfMaterial(Material.CIRCUITS)))
land(cart);
int mountPrevention = data.getInteger("MountPrevention");
if (mountPrevention > 0) {
mountPrevention--;
data.setInteger("MountPrevention", mountPrevention);
}
byte elevator = data.getByte("elevator");
if (elevator < BlockTrackElevator.ELEVATOR_TIMER) {
cart.setNoGravity(false);
}
if (elevator > 0) {
elevator--;
data.setByte("elevator", elevator);
}
byte derail = data.getByte("derail");
if (derail > 0) {
derail--;
data.setByte("derail", derail);
}
if (data.getBoolean("explode")) {
cart.getEntityData().setBoolean("explode", false);
CartTools.explodeCart(cart);
}
if (data.getBoolean(CartTools.HIGH_SPEED_TAG))
if (CartTools.cartVelocityIsLessThan(cart, HighSpeedTools.SPEED_CUTOFF))
data.setBoolean(CartTools.HIGH_SPEED_TAG, false);
else if (data.getInteger("Launched") == 0)
HighSpeedTools.checkSafetyAndExplode(cart.worldObj, event.getPos(), cart);
cart.motionX = Math.copySign(Math.min(Math.abs(cart.motionX), 9.5), cart.motionX);
cart.motionY = Math.copySign(Math.min(Math.abs(cart.motionY), 9.5), cart.motionY);
cart.motionZ = Math.copySign(Math.min(Math.abs(cart.motionZ), 9.5), cart.motionZ);
// List entities = cart.worldObj.getEntitiesWithinAABB(EntityLiving.class, getMinecartCollisionBox(cart, COLLISION_EXPANSION));
//
// if (entities != null) {
// for (Entity entity : (List<Entity>) entities) {
// if (entity != cart.riddenByEntity && entity.canBePushed()) {
// cart.applyEntityCollision(entity);
// }
// }
// }
}
Aggregations