Search in sources :

Example 11 with MovingObjectPosition

use of net.minecraft.util.MovingObjectPosition 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;
}
Also used : AxisAlignedBB(net.minecraft.util.AxisAlignedBB) Entity(net.minecraft.entity.Entity) EnumFacing(net.minecraft.util.EnumFacing) DiscreteMovementCommand(com.microsoft.Malmo.Schemas.DiscreteMovementCommand) BlockPos(net.minecraft.util.BlockPos) IBlockState(net.minecraft.block.state.IBlockState) MovingObjectPosition(net.minecraft.util.MovingObjectPosition) PlayerInteractEvent(net.minecraftforge.event.entity.player.PlayerInteractEvent) Event(net.minecraftforge.fml.common.eventhandler.Event) BlockEvent(net.minecraftforge.event.world.BlockEvent) Block(net.minecraft.block.Block) EntityPlayerSP(net.minecraft.client.entity.EntityPlayerSP) ItemStack(net.minecraft.item.ItemStack)

Example 12 with MovingObjectPosition

use of net.minecraft.util.MovingObjectPosition in project malmo by Microsoft.

the class ObservationFromRayImplementation method buildMouseOverData.

/** Build the json object for the object under the cursor, whether it is a block or a creature.<br>
     * If there is any data to be returned, the json will be added in a subnode called "LineOfSight".
     * @param json a JSON object into which the info for the object under the mouse will be added.
     */
public static void buildMouseOverData(JsonObject json) {
    // We could use Minecraft.getMinecraft().objectMouseOver but it's limited to the block reach distance, and
    // doesn't register floating tile items.
    // Ideally use Minecraft.timer.renderPartialTicks - but we don't need sub-tick resolution.
    float partialTicks = 0;
    Entity viewer = Minecraft.getMinecraft().thePlayer;
    // Hard-coded for now - in future will be parameterised via the XML.
    float depth = 50;
    Vec3 eyePos = viewer.getPositionEyes(partialTicks);
    Vec3 lookVec = viewer.getLook(partialTicks);
    Vec3 searchVec = eyePos.addVector(lookVec.xCoord * depth, lookVec.yCoord * depth, lookVec.zCoord * depth);
    MovingObjectPosition mop = Minecraft.getMinecraft().theWorld.rayTraceBlocks(eyePos, searchVec, false, false, false);
    MovingObjectPosition mopEnt = findEntity(eyePos, lookVec, depth, mop, true);
    if (mopEnt != null)
        mop = mopEnt;
    if (mop == null) {
        // Nothing under the mouse.
        return;
    }
    // Calculate ranges for player interaction:
    double hitDist = mop.hitVec.distanceTo(eyePos);
    double blockReach = Minecraft.getMinecraft().playerController.getBlockReachDistance();
    double entityReach = Minecraft.getMinecraft().playerController.extendedReach() ? 6.0 : 3.0;
    JsonObject jsonMop = new JsonObject();
    if (mop.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) {
        // We're looking at a block - send block data:
        jsonMop.addProperty("hitType", "block");
        jsonMop.addProperty("x", mop.hitVec.xCoord);
        jsonMop.addProperty("y", mop.hitVec.yCoord);
        jsonMop.addProperty("z", mop.hitVec.zCoord);
        IBlockState state = Minecraft.getMinecraft().theWorld.getBlockState(mop.getBlockPos());
        List<IProperty> extraProperties = new ArrayList<IProperty>();
        DrawBlock db = MinecraftTypeHelper.getDrawBlockFromBlockState(state, extraProperties);
        jsonMop.addProperty("type", db.getType().value());
        if (db.getColour() != null)
            jsonMop.addProperty("colour", db.getColour().value());
        if (db.getVariant() != null)
            jsonMop.addProperty("variant", db.getVariant().getValue());
        if (db.getFace() != null)
            jsonMop.addProperty("facing", db.getFace().value());
        if (extraProperties.size() > 0) {
            // Add the extra properties that aren't covered by colour/variant/facing.
            for (IProperty prop : extraProperties) {
                String key = "prop_" + prop.getName();
                if (prop.getValueClass() == Boolean.class)
                    jsonMop.addProperty(key, Boolean.valueOf(state.getValue(prop).toString()));
                else if (prop.getValueClass() == Integer.class)
                    jsonMop.addProperty(key, Integer.valueOf(state.getValue(prop).toString()));
                else
                    jsonMop.addProperty(key, state.getValue(prop).toString());
            }
        }
        jsonMop.addProperty("inRange", hitDist <= blockReach);
        jsonMop.addProperty("distance", hitDist);
    } else if (mop.typeOfHit == MovingObjectPosition.MovingObjectType.ENTITY) {
        // Looking at an entity:
        Entity entity = mop.entityHit;
        if (entity != null) {
            jsonMop.addProperty("x", entity.posX);
            jsonMop.addProperty("y", entity.posY);
            jsonMop.addProperty("z", entity.posZ);
            String name = entity.getName();
            String hitType = "entity";
            if (entity instanceof EntityItem) {
                ItemStack is = ((EntityItem) entity).getEntityItem();
                DrawItem di = MinecraftTypeHelper.getDrawItemFromItemStack(is);
                if (di.getColour() != null)
                    jsonMop.addProperty("colour", di.getColour().value());
                if (di.getVariant() != null)
                    jsonMop.addProperty("variant", di.getVariant().getValue());
                jsonMop.addProperty("stackSize", is.stackSize);
                name = di.getType();
                hitType = "item";
            }
            jsonMop.addProperty("type", name);
            jsonMop.addProperty("hitType", hitType);
        }
        jsonMop.addProperty("inRange", hitDist <= entityReach);
        jsonMop.addProperty("distance", hitDist);
    }
    json.add("LineOfSight", jsonMop);
}
Also used : Entity(net.minecraft.entity.Entity) IBlockState(net.minecraft.block.state.IBlockState) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) MovingObjectPosition(net.minecraft.util.MovingObjectPosition) IProperty(net.minecraft.block.properties.IProperty) Vec3(net.minecraft.util.Vec3) DrawItem(com.microsoft.Malmo.Schemas.DrawItem) DrawBlock(com.microsoft.Malmo.Schemas.DrawBlock) ItemStack(net.minecraft.item.ItemStack) EntityItem(net.minecraft.entity.item.EntityItem)

Example 13 with MovingObjectPosition

use of net.minecraft.util.MovingObjectPosition in project malmo by Microsoft.

the class ObservationFromRayImplementation method findEntity.

static MovingObjectPosition findEntity(Vec3 eyePos, Vec3 lookVec, double depth, MovingObjectPosition mop, boolean includeTiles) {
    // Based on code in EntityRenderer.getMouseOver()
    if (mop != null)
        depth = mop.hitVec.distanceTo(eyePos);
    Vec3 searchVec = eyePos.addVector(lookVec.xCoord * depth, lookVec.yCoord * depth, lookVec.zCoord * depth);
    Entity pointedEntity = null;
    Vec3 hitVec = null;
    Entity viewer = Minecraft.getMinecraft().thePlayer;
    List<?> list = Minecraft.getMinecraft().theWorld.getEntitiesWithinAABBExcludingEntity(viewer, viewer.getEntityBoundingBox().addCoord(lookVec.xCoord * depth, lookVec.yCoord * depth, lookVec.zCoord * depth).expand(1.0, 1.0, 1.0));
    double distance = depth;
    for (int i = 0; i < list.size(); ++i) {
        Entity entity = (Entity) list.get(i);
        if (entity.canBeCollidedWith() || includeTiles) {
            float border = entity.getCollisionBorderSize();
            AxisAlignedBB axisalignedbb = entity.getEntityBoundingBox().expand((double) border, (double) border, (double) border);
            MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(eyePos, searchVec);
            if (axisalignedbb.isVecInside(eyePos)) {
                // If entity is right inside our head?
                if (distance >= 0) {
                    pointedEntity = entity;
                    hitVec = (movingobjectposition == null) ? eyePos : mop.hitVec;
                    distance = 0.0D;
                }
            } else if (movingobjectposition != null) {
                double distToEnt = eyePos.distanceTo(movingobjectposition.hitVec);
                if (distToEnt < distance || distance == 0.0D) {
                    if (entity == entity.ridingEntity && !entity.canRiderInteract()) {
                        if (distance == 0.0D) {
                            pointedEntity = entity;
                            hitVec = movingobjectposition.hitVec;
                        }
                    } else {
                        pointedEntity = entity;
                        hitVec = movingobjectposition.hitVec;
                        distance = distToEnt;
                    }
                }
            }
        }
    }
    if (pointedEntity != null && (distance < depth || mop == null)) {
        MovingObjectPosition newMop = new MovingObjectPosition(pointedEntity, hitVec);
        return newMop;
    }
    return null;
}
Also used : AxisAlignedBB(net.minecraft.util.AxisAlignedBB) Entity(net.minecraft.entity.Entity) MovingObjectPosition(net.minecraft.util.MovingObjectPosition) Vec3(net.minecraft.util.Vec3)

Example 14 with MovingObjectPosition

use of net.minecraft.util.MovingObjectPosition in project PneumaticCraft by MineMaarten.

the class BlockElevatorCaller method collisionRayTrace.

@Override
public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 origin, Vec3 direction) {
    setBlockBounds(0, 0, 0, 1, 1, 1);
    MovingObjectPosition rayTrace = super.collisionRayTrace(world, x, y, z, origin, direction);
    ForgeDirection orientation = ForgeDirection.getOrientation(world.getBlockMetadata(x, y, z) & 7).getOpposite();
    if (rayTrace != null && rayTrace.sideHit == orientation.ordinal()) {
        TileEntity te = world.getTileEntity(x, y, z);
        if (te instanceof TileEntityElevatorCaller) {
            TileEntityElevatorCaller caller = (TileEntityElevatorCaller) te;
            for (TileEntityElevatorCaller.ElevatorButton button : caller.getFloors()) {
                float startX = 0, startZ = 0, endX = 0, endZ = 0;
                switch(orientation) {
                    case NORTH:
                        startZ = 0F;
                        endZ = 0.01F;
                        endX = 1 - (float) button.posX;
                        startX = 1 - ((float) button.posX + (float) button.width);
                        break;
                    case SOUTH:
                        startZ = 0.99F;
                        endZ = 1F;
                        startX = (float) button.posX;
                        endX = (float) button.posX + (float) button.width;
                        break;
                    case WEST:
                        startX = 0F;
                        endX = 0.01F;
                        startZ = (float) button.posX;
                        endZ = (float) button.posX + (float) button.width;
                        break;
                    case EAST:
                        startX = 0.99F;
                        endX = 1F;
                        endZ = 1 - (float) button.posX;
                        startZ = 1 - ((float) button.posX + (float) button.width);
                        break;
                }
                setBlockBounds(startX, 1 - (float) (button.posY + button.height), startZ, endX, 1 - (float) button.posY, endZ);
                MovingObjectPosition buttonTrace = super.collisionRayTrace(world, x, y, z, origin, direction);
                if (buttonTrace != null) {
                    if (startX > 0.01F && startX < 0.98F)
                        startX += 0.01F;
                    if (startZ > 0.01F && startZ < 0.98F)
                        startZ += 0.01F;
                    if (endX > 0.02F && endX < 0.99F)
                        endX -= 0.01F;
                    if (endZ > 0.02F && endZ < 0.99F)
                        endZ -= 0.01F;
                    setBlockBounds(startX, 1.01F - (float) (button.posY + button.height), startZ, endX, 0.99F - (float) button.posY, endZ);
                    buttonTrace.subHit = button.floorNumber;
                    return buttonTrace;
                }
            }
        }
    }
    setBlockBounds(0, 0, 0, 1, 1, 1);
    return rayTrace;
}
Also used : TileEntity(net.minecraft.tileentity.TileEntity) MovingObjectPosition(net.minecraft.util.MovingObjectPosition) ForgeDirection(net.minecraftforge.common.util.ForgeDirection) TileEntityElevatorCaller(pneumaticCraft.common.tileentity.TileEntityElevatorCaller)

Example 15 with MovingObjectPosition

use of net.minecraft.util.MovingObjectPosition in project PneumaticCraft by MineMaarten.

the class EventHandlerPneumaticCraft method FillBucket.

@SubscribeEvent
public void FillBucket(FillBucketEvent event) {
    MovingObjectPosition p = event.target;
    if (event.current == null || event.current.getItem() != Items.bucket || event.world.getBlockMetadata(p.blockX, p.blockY, p.blockZ) != 0)
        return;
    ItemStack result = attemptFill(event.world, event.target);
    if (result != null) {
        event.result = result;
        AchievementHandler.giveAchievement(event.entityPlayer, result);
        event.setResult(Result.ALLOW);
    }
}
Also used : MovingObjectPosition(net.minecraft.util.MovingObjectPosition) ItemStack(net.minecraft.item.ItemStack) SubscribeEvent(cpw.mods.fml.common.eventhandler.SubscribeEvent)

Aggregations

MovingObjectPosition (net.minecraft.util.MovingObjectPosition)60 Vec3 (net.minecraft.util.Vec3)19 Entity (net.minecraft.entity.Entity)17 EntityPlayer (net.minecraft.entity.player.EntityPlayer)17 AxisAlignedBB (net.minecraft.util.AxisAlignedBB)17 ItemStack (net.minecraft.item.ItemStack)16 TileEntity (net.minecraft.tileentity.TileEntity)16 ArrayList (java.util.ArrayList)11 ForgeDirection (net.minecraftforge.common.util.ForgeDirection)10 Block (net.minecraft.block.Block)8 EntityLivingBase (net.minecraft.entity.EntityLivingBase)7 AMVector3 (am2.api.math.AMVector3)5 World (net.minecraft.world.World)5 SubscribeEvent (cpw.mods.fml.common.eventhandler.SubscribeEvent)4 List (java.util.List)4 SpellCastResult (am2.api.spell.enums.SpellCastResult)3 ParticleApproachPoint (am2.particles.ParticleApproachPoint)3 IBlockState (net.minecraft.block.state.IBlockState)3 AMParticle (am2.particles.AMParticle)2 PacketPlayerItem (com.builtbroken.mc.core.network.packet.PacketPlayerItem)2