Search in sources :

Example 21 with LanternPlayer

use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.

the class LanternWorld method broadcast.

public void broadcast(Supplier<Message> message, @Nullable Predicate<LanternPlayer> filter) {
    Set<LanternPlayer> players = this.players;
    if (filter != null) {
        players = players.stream().filter(filter).collect(Collectors.toSet());
    }
    if (players.isEmpty()) {
        return;
    }
    final Message message0 = message.get();
    players.forEach(player -> player.getConnection().send(message0));
}
Also used : Message(org.lanternpowered.server.network.message.Message) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 22 with LanternPlayer

use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.

the class ConsumableInteractionBehavior method tryUse.

@Override
public BehaviorResult tryUse(BehaviorPipeline<Behavior> pipeline, BehaviorContext context) {
    final Optional<Player> optPlayer = context.getContext(ContextKeys.PLAYER);
    if (optPlayer.isPresent()) {
        final Player player = optPlayer.get();
        final ItemStack itemStack = context.requireContext(ContextKeys.USED_ITEM_STACK);
        final FoodRestorationProperty foodRestorationProperty = itemStack.getProperty(FoodRestorationProperty.class).orElse(null);
        if (foodRestorationProperty != null && foodRestorationProperty.getValue() != 0.0) {
            final Optional<Integer> maxFood = player.get(LanternKeys.MAX_FOOD_LEVEL);
            final Optional<Integer> optFoodLevel = player.get(Keys.FOOD_LEVEL);
            if (optFoodLevel.isPresent()) {
                player.offer(Keys.FOOD_LEVEL, Math.min(optFoodLevel.get() + foodRestorationProperty.getValue(), maxFood.orElse(Integer.MAX_VALUE)));
            }
        }
        final HealthRestorationProperty healthRestorationProperty = itemStack.getProperty(HealthRestorationProperty.class).orElse(null);
        if (healthRestorationProperty != null && healthRestorationProperty.getValue() != 0.0) {
            final Optional<Double> maxHealth = player.get(Keys.MAX_HEALTH);
            final Optional<Double> optHealth = player.get(Keys.HEALTH);
            if (optHealth.isPresent()) {
                player.offer(Keys.HEALTH, Math.min(optHealth.get() + healthRestorationProperty.getValue(), maxHealth.orElse(Double.MAX_VALUE)));
            }
        }
        final SaturationProperty saturationProperty = itemStack.getProperty(SaturationProperty.class).orElse(null);
        if (saturationProperty != null && saturationProperty.getValue() != 0.0) {
            final Optional<Double> optSaturation = player.get(Keys.SATURATION);
            if (optSaturation.isPresent()) {
                player.offer(Keys.SATURATION, Math.min(optSaturation.get() + saturationProperty.getValue(), player.get(Keys.FOOD_LEVEL).orElse(20)));
            }
        }
        final ApplicableEffectProperty applicableEffectProperty = itemStack.getProperty(ApplicableEffectProperty.class).orElse(null);
        if (applicableEffectProperty != null && !applicableEffectProperty.getValue().isEmpty()) {
            final List<PotionEffect> potionEffects = player.get(Keys.POTION_EFFECTS).orElse(Collections.emptyList());
            player.offer(Keys.POTION_EFFECTS, PotionEffectHelper.merge(potionEffects, applicableEffectProperty.getValue()));
        }
        if (this.consumer != null) {
            this.consumer.apply(player, pipeline, context);
        }
        if (!player.get(Keys.GAME_MODE).orElse(GameModes.NOT_SET).equals(GameModes.CREATIVE)) {
            final Slot slot = context.requireContext(ContextKeys.USED_SLOT);
            slot.poll(1);
            if (this.restItemSupplier != null) {
                if (slot.peek().isPresent()) {
                    ((LanternPlayer) player).getInventory().getMain().offer(this.restItemSupplier.get());
                } else {
                    slot.set(this.restItemSupplier.get());
                }
            }
        }
        return BehaviorResult.SUCCESS;
    }
    return BehaviorResult.PASS;
}
Also used : SaturationProperty(org.spongepowered.api.data.property.item.SaturationProperty) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer) Player(org.spongepowered.api.entity.living.player.Player) PotionEffect(org.spongepowered.api.effect.potion.PotionEffect) FoodRestorationProperty(org.spongepowered.api.data.property.item.FoodRestorationProperty) HealthRestorationProperty(org.lanternpowered.server.item.property.HealthRestorationProperty) Slot(org.spongepowered.api.item.inventory.Slot) ApplicableEffectProperty(org.spongepowered.api.data.property.item.ApplicableEffectProperty) ItemStack(org.spongepowered.api.item.inventory.ItemStack) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 23 with LanternPlayer

use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.

the class LanternServer method shutdown.

@SuppressWarnings("deprecation")
@Override
public void shutdown(Text kickMessage) {
    checkNotNull(kickMessage, "kickMessage");
    if (this.shuttingDown) {
        return;
    }
    this.shuttingDown = true;
    // Stop the console
    this.consoleManager.shutdown();
    final Cause gameCause = Cause.of(EventContext.empty(), this.game);
    this.game.postGameStateChange(SpongeEventFactory.createGameStoppingServerEvent(gameCause));
    // Debug a message
    this.logger.info("Stopping the server... ({})", LanternTexts.toLegacy(kickMessage));
    // Kick all the online players
    getOnlinePlayers().forEach(player -> ((LanternPlayer) player).getConnection().disconnect(kickMessage));
    // Stop the network servers - starts the shutdown process
    // It may take a second or two for Netty to totally clean up
    this.networkManager.shutdown();
    if (this.queryServer != null) {
        this.queryServer.shutdown();
    }
    if (this.rconServer != null) {
        this.rconServer.shutdown();
    }
    // Stop the world manager
    this.worldManager.shutdown();
    // Shutdown the executor
    this.executor.shutdown();
    // Stop the async scheduler
    this.game.getScheduler().shutdownAsyncScheduler(10, TimeUnit.SECONDS);
    final Collection<ProviderRegistration<?>> serviceRegistrations;
    try {
        final ServiceManager serviceManager = this.game.getServiceManager();
        checkState(serviceManager instanceof SimpleServiceManager || serviceManager instanceof LanternServiceManager);
        final Field field = (serviceManager instanceof SimpleServiceManager ? SimpleServiceManager.class : LanternServiceManager.class).getDeclaredField("providers");
        field.setAccessible(true);
        // noinspection unchecked
        final Map<Class<?>, ProviderRegistration<?>> map = (Map<Class<?>, ProviderRegistration<?>>) field.get(serviceManager);
        serviceRegistrations = map.values();
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
    // Close all the services if possible
    serviceRegistrations.forEach(provider -> {
        final Object service = provider.getProvider();
        if (service instanceof CloseableService) {
            try {
                ((CloseableService) service).close();
            } catch (Exception e) {
                this.logger.error("A error occurred while closing the {}.", provider.getService().getName(), e);
            }
        }
    });
    // Shutdown the game profile manager
    this.game.getGameProfileManager().getDefaultCache().save();
    final GameProfileCache cache = this.game.getGameProfileManager().getCache();
    if (cache instanceof CloseableService) {
        try {
            ((CloseableService) cache).close();
        } catch (Exception e) {
            this.logger.error("A error occurred while closing the GameProfileCache.", e);
        }
    }
    try {
        this.game.getOpsConfig().save();
    } catch (IOException e) {
        this.logger.error("A error occurred while saving the ops config.", e);
    }
    this.game.postGameStateChange(SpongeEventFactory.createGameStoppedServerEvent(gameCause));
    this.game.postGameStateChange(SpongeEventFactory.createGameStoppingEvent(gameCause));
    this.game.postGameStateChange(SpongeEventFactory.createGameStoppedEvent(gameCause));
    // Wait for a while and terminate any rogue threads
    new ShutdownMonitorThread().start();
}
Also used : LanternServiceManager(org.lanternpowered.server.service.LanternServiceManager) GameProfileCache(org.spongepowered.api.profile.GameProfileCache) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BindException(java.net.BindException) IOException(java.io.IOException) Field(java.lang.reflect.Field) CloseableService(org.lanternpowered.server.service.CloseableService) LanternServiceManager(org.lanternpowered.server.service.LanternServiceManager) SimpleServiceManager(org.spongepowered.api.service.SimpleServiceManager) ServiceManager(org.spongepowered.api.service.ServiceManager) Cause(org.spongepowered.api.event.cause.Cause) ShutdownMonitorThread(org.lanternpowered.server.util.ShutdownMonitorThread) ProviderRegistration(org.spongepowered.api.service.ProviderRegistration) SimpleServiceManager(org.spongepowered.api.service.SimpleServiceManager) Map(java.util.Map) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 24 with LanternPlayer

use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.

the class LanternLiving method handleDeath.

private void handleDeath() {
    // have already been thrown.
    if (getWorld() == null) {
        setDead(true);
    }
    if (isDead()) {
        return;
    }
    setDead(true);
    final CauseStack causeStack = CauseStack.current();
    // Only players can keep their inventory
    final boolean keepsInventory = this instanceof LanternPlayer && getWorld().getOrCreateRule(RuleTypes.KEEP_INVENTORY).getValue();
    // Post the entity destruction event
    final DestructEntityEvent.Death event = SpongeEventFactory.createDestructEntityEventDeath(causeStack.getCurrentCause(), MessageChannel.TO_NONE, Optional.empty(), new MessageEvent.MessageFormatter(), this, keepsInventory, false);
    postDestructEvent(event);
    try (CauseStack.Frame frame = causeStack.pushCauseFrame()) {
        // Add the destruct event to the cause, this can be used
        // to track the cause of the entity death.
        frame.pushCause(event);
        // Post the harvest event
        handleDeath(causeStack);
    }
    // Clear the inventory, if keepsInventory is false in the thrown Death event
    if (!event.getKeepInventory() && this instanceof Carrier) {
        ((Carrier) this).getInventory().clear();
    }
}
Also used : CauseStack(org.lanternpowered.server.event.CauseStack) DestructEntityEvent(org.spongepowered.api.event.entity.DestructEntityEvent) MessageEvent(org.spongepowered.api.event.message.MessageEvent) Carrier(org.spongepowered.api.item.inventory.Carrier) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 25 with LanternPlayer

use of org.lanternpowered.server.entity.living.player.LanternPlayer in project LanternServer by LanternPowered.

the class VanillaContainerInteractionBehavior method handleShiftClick.

@Override
public void handleShiftClick(ClientContainer clientContainer, ClientSlot clientSlot, MouseButton mouseButton) {
    final LanternPlayer player = clientContainer.getPlayer();
    if (player != this.container.getPlayerInventory().getCarrier().orElse(null) || !(clientSlot instanceof ClientSlot.Slot) || mouseButton == MouseButton.MIDDLE) {
        return;
    }
    final AbstractInventorySlot slot = ((ClientSlot.Slot) clientSlot).getSlot();
    final ItemStack itemStack = slot.peek().orElse(null);
    final Transaction<ItemStackSnapshot> cursorTransaction;
    final List<SlotTransaction> transactions = new ArrayList<>();
    if (slot instanceof CraftingOutput) {
        final ItemStackSnapshot cursorItem = LanternItemStack.toSnapshot(getCursorItem());
        cursorTransaction = new Transaction<>(cursorItem, cursorItem);
        final AbstractInventory parent = slot.parent();
        if (parent instanceof CraftingInventory) {
            final CraftingInventory inventory = (CraftingInventory) parent;
            final Optional<ExtendedCraftingResult> optResult = Lantern.getRegistry().getCraftingRecipeRegistry().getExtendedResult(inventory.getCraftingGrid(), player.getWorld());
            if (optResult.isPresent()) {
                final ExtendedCraftingResult result = optResult.get();
                final ItemStackSnapshot resultItem = result.getResult().getResult();
                int times = result.getMaxTimes();
                final ItemStack itemStack1 = resultItem.createStack();
                itemStack1.setQuantity(times * itemStack1.getQuantity());
                final AbstractInventory targetInventory = this.container.getPlayerInventory().getView(LanternPlayerInventory.View.REVERSE_MAIN_AND_HOTBAR);
                PeekedOfferTransactionResult peekResult = targetInventory.peekOffer(itemStack1);
                if (peekResult.isSuccess()) {
                    transactions.add(new SlotTransaction(slot, resultItem, ItemStackSnapshot.NONE));
                    final ItemStack rejectedItem = peekResult.getRejectedItem().orElse(null);
                    if (rejectedItem != null) {
                        final int added = itemStack1.getQuantity() - rejectedItem.getQuantity();
                        times = added / resultItem.getQuantity();
                        final int diff = added % resultItem.getQuantity();
                        if (diff != 0) {
                            itemStack1.setQuantity(resultItem.getQuantity() * times);
                            peekResult = targetInventory.peekOffer(itemStack1);
                            checkState(peekResult.isSuccess());
                        }
                    }
                    transactions.addAll(peekResult.getTransactions());
                    updateCraftingGrid(player, inventory, result.getMatrixResult(times), transactions);
                }
            } else {
                // No actual transaction, there shouldn't have been a item in the crafting result slot
                transactions.add(new SlotTransaction(slot, ItemStackSnapshot.NONE, ItemStackSnapshot.NONE));
            }
        } else {
            Lantern.getLogger().warn("Found a CraftingOutput slot without a CraftingInventory as parent.");
            return;
        }
    } else {
        final ItemStackSnapshot cursorItem = LanternItemStack.toSnapshot(getCursorItem());
        cursorTransaction = new Transaction<>(cursorItem, cursorItem);
        if (itemStack != null) {
            final IInventory target = this.container.getOpenInventory().getShiftClickBehavior().getTarget(this.container, slot);
            final PeekedOfferTransactionResult result = target.peekOffer(itemStack.copy());
            if (result.isSuccess()) {
                transactions.addAll(result.getTransactions());
                final ItemStack rejectedItem = result.getRejectedItem().orElse(null);
                if (rejectedItem != null) {
                    slot.peekPoll(itemStack.getQuantity() - rejectedItem.getQuantity(), stack -> true).ifPresent(peekResult -> transactions.addAll(peekResult.getTransactions()));
                } else {
                    slot.peekPoll(stack -> true).ifPresent(peekResult -> transactions.addAll(peekResult.getTransactions()));
                }
            }
        }
    }
    final List<SlotTransaction> transactions1 = this.container.transformSlots(transactions);
    final CauseStack causeStack = CauseStack.current();
    final ClickInventoryEvent.Shift event;
    if (mouseButton == MouseButton.LEFT) {
        event = SpongeEventFactory.createClickInventoryEventShiftPrimary(causeStack.getCurrentCause(), cursorTransaction, this.container, transactions1);
    } else {
        event = SpongeEventFactory.createClickInventoryEventShiftSecondary(causeStack.getCurrentCause(), cursorTransaction, this.container, transactions1);
    }
    finishInventoryEvent(event);
}
Also used : CraftingInventory(org.spongepowered.api.item.inventory.crafting.CraftingInventory) IInventory(org.lanternpowered.server.inventory.IInventory) EventContextKeys(org.spongepowered.api.event.cause.EventContextKeys) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) LanternPlayerInventory(org.lanternpowered.server.inventory.vanilla.LanternPlayerInventory) LanternItemStackSnapshot(org.lanternpowered.server.inventory.LanternItemStackSnapshot) CraftingResult(org.spongepowered.api.item.recipe.crafting.CraftingResult) ItemStack(org.spongepowered.api.item.inventory.ItemStack) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction) ClickInventoryEvent(org.spongepowered.api.event.item.inventory.ClickInventoryEvent) Transaction(org.spongepowered.api.data.Transaction) OutputSlot(org.spongepowered.api.item.inventory.slot.OutputSlot) ExtendedCraftingResult(org.lanternpowered.server.item.recipe.crafting.ExtendedCraftingResult) AbstractSlot(org.lanternpowered.server.inventory.AbstractSlot) MatrixResult(org.lanternpowered.server.item.recipe.crafting.MatrixResult) Sponge(org.spongepowered.api.Sponge) CraftingGridInventory(org.spongepowered.api.item.inventory.crafting.CraftingGridInventory) Tuple(org.spongepowered.api.util.Tuple) Streams(com.google.common.collect.Streams) CraftingOutput(org.spongepowered.api.item.inventory.crafting.CraftingOutput) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) Lantern(org.lanternpowered.server.game.Lantern) Transform(org.spongepowered.api.entity.Transform) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) ChangeInventoryEvent(org.spongepowered.api.event.item.inventory.ChangeInventoryEvent) CraftingInventory(org.spongepowered.api.item.inventory.crafting.CraftingInventory) World(org.spongepowered.api.world.World) Optional(java.util.Optional) AbstractOrderedInventory(org.lanternpowered.server.inventory.AbstractOrderedInventory) Player(org.spongepowered.api.entity.living.player.Player) LanternItemStack(org.lanternpowered.server.inventory.LanternItemStack) ClientContainer(org.lanternpowered.server.inventory.client.ClientContainer) IInventory(org.lanternpowered.server.inventory.IInventory) Keys(org.spongepowered.api.data.key.Keys) PeekedSetTransactionResult(org.lanternpowered.server.inventory.PeekedSetTransactionResult) GameModes(org.spongepowered.api.entity.living.player.gamemode.GameModes) ArrayList(java.util.ArrayList) CauseStack(org.lanternpowered.server.event.CauseStack) PlayerInventoryContainer(org.lanternpowered.server.inventory.PlayerInventoryContainer) LanternContainer(org.lanternpowered.server.inventory.LanternContainer) PlayerClientContainer(org.lanternpowered.server.inventory.client.PlayerClientContainer) LanternWorld(org.lanternpowered.server.world.LanternWorld) CraftingMatrix(org.lanternpowered.server.item.recipe.crafting.CraftingMatrix) Nullable(javax.annotation.Nullable) ClientSlot(org.lanternpowered.server.inventory.client.ClientSlot) AbstractInventorySlot(org.lanternpowered.server.inventory.AbstractInventorySlot) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) LanternEventHelper(org.lanternpowered.server.event.LanternEventHelper) PeekedPollTransactionResult(org.lanternpowered.server.inventory.PeekedPollTransactionResult) SpawnEntityEvent(org.spongepowered.api.event.entity.SpawnEntityEvent) Slot(org.spongepowered.api.item.inventory.Slot) Entity(org.spongepowered.api.entity.Entity) PeekedOfferTransactionResult(org.lanternpowered.server.inventory.PeekedOfferTransactionResult) SpawnTypes(org.spongepowered.api.event.cause.entity.spawn.SpawnTypes) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer) LanternHotbarInventory(org.lanternpowered.server.inventory.vanilla.LanternHotbarInventory) AbstractInventory(org.lanternpowered.server.inventory.AbstractInventory) CauseStack(org.lanternpowered.server.event.CauseStack) ExtendedCraftingResult(org.lanternpowered.server.item.recipe.crafting.ExtendedCraftingResult) CraftingOutput(org.spongepowered.api.item.inventory.crafting.CraftingOutput) ArrayList(java.util.ArrayList) PeekedOfferTransactionResult(org.lanternpowered.server.inventory.PeekedOfferTransactionResult) ClickInventoryEvent(org.spongepowered.api.event.item.inventory.ClickInventoryEvent) SlotTransaction(org.spongepowered.api.item.inventory.transaction.SlotTransaction) AbstractInventory(org.lanternpowered.server.inventory.AbstractInventory) OutputSlot(org.spongepowered.api.item.inventory.slot.OutputSlot) AbstractSlot(org.lanternpowered.server.inventory.AbstractSlot) ClientSlot(org.lanternpowered.server.inventory.client.ClientSlot) AbstractInventorySlot(org.lanternpowered.server.inventory.AbstractInventorySlot) Slot(org.spongepowered.api.item.inventory.Slot) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) LanternItemStackSnapshot(org.lanternpowered.server.inventory.LanternItemStackSnapshot) AbstractInventorySlot(org.lanternpowered.server.inventory.AbstractInventorySlot) ItemStack(org.spongepowered.api.item.inventory.ItemStack) LanternItemStack(org.lanternpowered.server.inventory.LanternItemStack) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Aggregations

LanternPlayer (org.lanternpowered.server.entity.living.player.LanternPlayer)48 ArrayList (java.util.ArrayList)13 CauseStack (org.lanternpowered.server.event.CauseStack)12 AbstractSlot (org.lanternpowered.server.inventory.AbstractSlot)11 ItemStack (org.spongepowered.api.item.inventory.ItemStack)11 World (org.spongepowered.api.world.World)11 Optional (java.util.Optional)10 Vector3d (com.flowpowered.math.vector.Vector3d)9 List (java.util.List)9 Collectors (java.util.stream.Collectors)9 Nullable (javax.annotation.Nullable)9 Sponge (org.spongepowered.api.Sponge)9 SlotTransaction (org.spongepowered.api.item.inventory.transaction.SlotTransaction)9 Lantern (org.lanternpowered.server.game.Lantern)8 LanternItemStack (org.lanternpowered.server.inventory.LanternItemStack)8 Player (org.spongepowered.api.entity.living.player.Player)8 ChangeInventoryEvent (org.spongepowered.api.event.item.inventory.ChangeInventoryEvent)8 AbstractInventory (org.lanternpowered.server.inventory.AbstractInventory)7 PlayerInventoryContainer (org.lanternpowered.server.inventory.PlayerInventoryContainer)7 ClientContainer (org.lanternpowered.server.inventory.client.ClientContainer)7