Lots more moved

This commit is contained in:
Sebastian Hartte
2020-07-04 21:03:30 +02:00
parent 5982f094ec
commit 1478e4c378
444 changed files with 4693 additions and 5235 deletions
@@ -0,0 +1,157 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.misc;
import java.util.List;
import javax.annotation.Nullable;
import appeng.core.AppEng;
import com.google.common.base.Preconditions;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.client.model.FabricModelPredicateProviderRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.Material;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemConvertible;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Identifier;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.math.MathHelper;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import appeng.api.implementations.items.IGrowableCrystal;
import appeng.core.localization.ButtonToolTips;
import appeng.entity.GrowingCrystalEntity;
import appeng.items.AEBaseItem;
/**
* This item reprents one of the seeds used to grow various forms of quartz by
* throwing them into water (for that behavior, see the linked entity)
*/
public class CrystalSeedItem extends AEBaseItem implements IGrowableCrystal {
/**
* Name of NBT tag used to store the growth progress value.
*/
private static final String TAG_GROWTH_TICKS = "p";
/**
* The number of growth ticks required to finish growing.
*/
private static final int GROWTH_TICKS_REQUIRED = 600;
/**
* The item to convert to, when growth finishes.
*/
private final ItemConvertible grownItem;
public CrystalSeedItem(Settings properties, ItemConvertible grownItem) {
super(properties);
this.grownItem = Preconditions.checkNotNull(grownItem);
// Expose the growth of the seed to the model system
FabricModelPredicateProviderRegistry.register(
this,
new Identifier(AppEng.MOD_ID, "growth"),
(is, w, p) -> getGrowthTicks(is) / (float) GROWTH_TICKS_REQUIRED
);
}
@Nullable
@Override
public ItemStack triggerGrowth(final ItemStack is) {
final int growthTicks = getGrowthTicks(is) + 1;
if (growthTicks >= GROWTH_TICKS_REQUIRED) {
return new ItemStack(grownItem, is.getCount());
} else {
this.setGrowthTicks(is, growthTicks);
return is;
}
}
private static int getGrowthTicks(final ItemStack is) {
CompoundTag tag = is.getTag();
return tag != null ? tag.getInt(TAG_GROWTH_TICKS) : 0;
}
private void setGrowthTicks(final ItemStack is, int ticks) {
ticks = MathHelper.clamp(ticks, 0, GROWTH_TICKS_REQUIRED);
is.getOrCreateTag().putInt(TAG_GROWTH_TICKS, ticks);
}
@Override
public float getMultiplier(final Block blk, final Material mat) {
return 0.5f;
}
@Override
@Environment(EnvType.CLIENT)
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
lines.add(ButtonToolTips.DoesntDespawn.text());
lines.add(getGrowthTooltipItem(stack));
super.appendTooltip(stack, world, lines, advancedTooltips);
}
public Text getGrowthTooltipItem(ItemStack stack) {
final int progress = getGrowthTicks(stack);
return new LiteralText(Math.round(100 * progress / (float) GROWTH_TICKS_REQUIRED) + "%");
}
// FIXME FABRIC Needs custom mixin
// FIXME FABRIC @Override
// FIXME FABRIC public boolean hasCustomEntity(final ItemStack stack) {
// FIXME FABRIC return true;
// FIXME FABRIC }
// FIXME FABRIC
// FIXME FABRIC @Override
// FIXME FABRIC public Entity createEntity(final World world, final Entity location, final ItemStack itemstack) {
// FIXME FABRIC final GrowingCrystalEntity egc = new GrowingCrystalEntity(world, location.getX(), location.getY(),
// FIXME FABRIC location.getZ(), itemstack);
// FIXME FABRIC
// FIXME FABRIC egc.setVelocity(location.getVelocity());
// FIXME FABRIC
// FIXME FABRIC // Cannot read the pickup delay of the original item, so we
// FIXME FABRIC // use the pickup delay used for items dropped by a player instead
// FIXME FABRIC egc.setPickupDelay(40);
// FIXME FABRIC
// FIXME FABRIC return egc;
// FIXME FABRIC }
@Override
public void appendStacks(ItemGroup group, DefaultedList<ItemStack> items) {
if (this.isIn(group)) {
// lvl 0
items.add(new ItemStack(this, 1));
// one tick before maturity
ItemStack almostFullGrown = new ItemStack(this, 1);
setGrowthTicks(almostFullGrown, GROWTH_TICKS_REQUIRED - 1);
items.add(almostFullGrown);
}
}
}
@@ -0,0 +1,209 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.misc;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import appeng.hooks.AEToolItem;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.text.LiteralText;
import net.minecraft.text.MutableText;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.world.World;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import appeng.api.AEApi;
import appeng.api.implementations.ICraftingPatternItem;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.storage.data.IAEItemStack;
import appeng.core.AppEng;
import appeng.core.localization.GuiText;
import appeng.helpers.InvalidPatternHelper;
import appeng.helpers.PatternHelper;
import appeng.items.AEBaseItem;
import appeng.util.Platform;
public class EncodedPatternItem extends AEBaseItem implements ICraftingPatternItem, AEToolItem {
// rather simple client side caching.
private static final Map<ItemStack, ItemStack> SIMPLE_CACHE = new WeakHashMap<>();
public EncodedPatternItem(Settings properties) {
super(properties);
}
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity player, final Hand hand) {
this.clearPattern(player.getStackInHand(hand), player);
return new TypedActionResult<>(ActionResult.SUCCESS, player.getStackInHand(hand));
}
@Override
public ActionResult onItemUseFirst(ItemStack stack, ItemUsageContext context) {
return this.clearPattern(stack, context.getPlayer()) ? ActionResult.SUCCESS : ActionResult.PASS;
}
private boolean clearPattern(final ItemStack stack, final PlayerEntity player) {
if (player.isInSneakingPose()) {
if (Platform.isClient()) {
return false;
}
final PlayerInventory inv = player.inventory;
ItemStack is = AEApi.instance().definitions().materials().blankPattern().maybeStack(stack.getCount())
.orElse(ItemStack.EMPTY);
if (!is.isEmpty()) {
for (int s = 0; s < player.inventory.size(); s++) {
if (inv.getStack(s) == stack) {
inv.setStack(s, is);
return true;
}
}
}
}
return false;
}
@Override
@Environment(EnvType.CLIENT)
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
final ICraftingPatternDetails details = this.getPatternForItem(stack, world);
if (details == null) {
if (!stack.hasTag()) {
return;
}
stack.setCustomName(GuiText.InvalidPattern.textComponent().copy().formatted(Formatting.RED));
InvalidPatternHelper invalid = new InvalidPatternHelper(stack);
final Text label = (invalid.isCraftable() ? GuiText.Crafts.textComponent()
: GuiText.Creates.textComponent()).copy().append(": ");
final Text and = new LiteralText(" ").append(GuiText.And.textComponent())
.append(" ");
final Text with = GuiText.With.textComponent().copy().append(": ");
boolean first = true;
for (final InvalidPatternHelper.PatternIngredient output : invalid.getOutputs()) {
lines.add((first ? label : and).copy().append(output.getFormattedToolTip()));
first = false;
}
first = true;
for (final InvalidPatternHelper.PatternIngredient input : invalid.getInputs()) {
lines.add((first ? with : and).copy().append(input.getFormattedToolTip()));
first = false;
}
if (invalid.isCraftable()) {
final MutableText substitutionLabel = GuiText.Substitute.textComponent().copy().append(" ");
final Text canSubstitute = invalid.canSubstitute() ? GuiText.Yes.textComponent()
: GuiText.No.textComponent();
lines.add(substitutionLabel.append(canSubstitute));
}
return;
}
if (stack.hasCustomName()) {
stack.removeSubTag("display");
}
final boolean isCrafting = details.isCraftable();
final boolean substitute = details.canSubstitute();
final IAEItemStack[] in = details.getCondensedInputs();
final IAEItemStack[] out = details.getCondensedOutputs();
final Text label = (isCrafting ? GuiText.Crafts.textComponent() : GuiText.Creates.textComponent())
.copy().append(": ");
final Text and = new LiteralText(" ").append(GuiText.And.textComponent())
.append(" ");
final Text with = GuiText.With.textComponent().copy().append(": ");
boolean first = true;
for (final IAEItemStack anOut : out) {
if (anOut == null) {
continue;
}
lines.add((first ? label : and).copy().append(anOut.getStackSize() + "x ")
.append(Platform.getItemDisplayName(anOut)));
first = false;
}
first = true;
for (final IAEItemStack anIn : in) {
if (anIn == null) {
continue;
}
lines.add((first ? with : and).copy().append(anIn.getStackSize() + "x ")
.append(Platform.getItemDisplayName(anIn)));
first = false;
}
if (isCrafting) {
final MutableText substitutionLabel = GuiText.Substitute.textComponent().copy().append(" ");
final Text canSubstitute = substitute ? GuiText.Yes.textComponent() : GuiText.No.textComponent();
lines.add(substitutionLabel.append(canSubstitute));
}
}
@Override
public ICraftingPatternDetails getPatternForItem(final ItemStack is, final World w) {
try {
return new PatternHelper(is, w);
} catch (final Throwable t) {
return null;
}
}
public ItemStack getOutput(World w, final ItemStack item) {
ItemStack out = SIMPLE_CACHE.get(item);
if (out != null) {
return out;
}
final ICraftingPatternDetails details = this.getPatternForItem(item, w);
out = details != null ? details.getOutputs()[0].createItemStack() : ItemStack.EMPTY;
SIMPLE_CACHE.put(item, out);
return out;
}
}
@@ -0,0 +1,44 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.misc;
import appeng.api.util.AEColor;
import appeng.items.AEBaseItem;
public class PaintBallItem extends AEBaseItem {
private final AEColor color;
private final boolean lumen;
public PaintBallItem(Settings properties, AEColor color, boolean lumen) {
super(properties);
this.color = color;
this.lumen = lumen;
}
public AEColor getColor() {
return color;
}
public boolean isLumen() {
return lumen;
}
}
@@ -0,0 +1,56 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.misc;
import appeng.api.util.AEColor;
import appeng.bootstrap.IItemRendering;
import appeng.bootstrap.ItemRenderingCustomizer;
public class PaintBallItemRendering extends ItemRenderingCustomizer {
private final boolean lumen;
private final AEColor color;
public PaintBallItemRendering(AEColor color, boolean lumen) {
this.lumen = lumen;
this.color = color;
}
@Override
public void customize(IItemRendering rendering) {
final int colorValue = lumen ? color.mediumVariant : color.mediumVariant;
final int r = (colorValue >> 16) & 0xff;
final int g = (colorValue >> 8) & 0xff;
final int b = (colorValue) & 0xff;
int renderColor;
if (lumen) {
final float fail = 0.7f;
final int full = (int) (255 * 0.3);
renderColor = (int) (full + r * fail) << 16 | (int) (full + g * fail) << 8 | (int) (full + b * fail)
| 0xff << 24;
} else {
renderColor = r << 16 | g << 8 | b | 0xff << 24;
}
rendering.color((is, tintIndex) -> renderColor);
}
}
@@ -0,0 +1,208 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2018, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.storage;
import java.util.List;
import java.util.Set;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import appeng.hooks.AEToolItem;
import net.fabricmc.api.EnvType;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import net.fabricmc.api.Environment;
import appeng.api.AEApi;
import appeng.api.config.FuzzyMode;
import appeng.api.exceptions.MissingDefinitionException;
import appeng.api.features.AEFeature;
import appeng.api.implementations.items.IStorageCell;
import appeng.api.implementations.items.IUpgradeModule;
import appeng.api.storage.IMEInventoryHandler;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.core.AEConfig;
import appeng.core.localization.GuiText;
import appeng.items.AEBaseItem;
import appeng.items.contents.CellConfig;
import appeng.items.contents.CellUpgrades;
import appeng.items.materials.MaterialType;
import appeng.util.InventoryAdaptor;
import appeng.util.Platform;
/**
* @author DrummerMC
* @version rv6 - 2018-01-17
* @since rv6 2018-01-17
*/
public abstract class AbstractStorageCell<T extends IAEStack<T>> extends AEBaseItem implements IStorageCell<T>, AEToolItem {
protected final MaterialType component;
protected final int totalBytes;
public AbstractStorageCell(Settings properties, final MaterialType whichCell, final int kilobytes) {
super(properties);
this.totalBytes = kilobytes * 1024;
this.component = whichCell;
}
@Environment(EnvType.CLIENT)
@Override
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
AEApi.instance().client().addCellInformation(
AEApi.instance().registries().cell().getCellInventory(stack, null, this.getChannel()), lines);
}
@Override
public int getBytes(final ItemStack cellItem) {
return this.totalBytes;
}
@Override
public int getTotalTypes(final ItemStack cellItem) {
return 63;
}
@Override
public boolean isBlackListed(final ItemStack cellItem, final T requestedAddition) {
return false;
}
@Override
public boolean storableInStorageCell() {
return false;
}
@Override
public boolean isStorageCell(final ItemStack i) {
return true;
}
@Override
public boolean isEditable(final ItemStack is) {
return true;
}
@Override
public FixedItemInv getUpgradesInventory(final ItemStack is) {
return new CellUpgrades(is, 2);
}
@Override
public FixedItemInv getConfigInventory(final ItemStack is) {
return new CellConfig(is);
}
@Override
public FuzzyMode getFuzzyMode(final ItemStack is) {
final String fz = is.getOrCreateTag().getString("FuzzyMode");
try {
return FuzzyMode.valueOf(fz);
} catch (final Throwable t) {
return FuzzyMode.IGNORE_ALL;
}
}
@Override
public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {
is.getOrCreateTag().putString("FuzzyMode", fzMode.name());
}
@Override
public TypedActionResult<ItemStack> use(final World world, final PlayerEntity player, final Hand hand) {
this.disassembleDrive(player.getStackInHand(hand), world, player);
return new TypedActionResult<>(ActionResult.SUCCESS, player.getStackInHand(hand));
}
private boolean disassembleDrive(final ItemStack stack, final World world, final PlayerEntity player) {
if (player.isInSneakingPose()) {
if (Platform.isClient()) {
return false;
}
final PlayerInventory playerInventory = player.inventory;
final IMEInventoryHandler inv = AEApi.instance().registries().cell().getCellInventory(stack, null,
this.getChannel());
if (inv != null && playerInventory.getMainHandStack() == stack) {
final InventoryAdaptor ia = InventoryAdaptor.getAdaptor(player);
final IItemList<IAEItemStack> list = inv.getAvailableItems(this.getChannel().createList());
if (list.isEmpty() && ia != null) {
playerInventory.setStack(playerInventory.selectedSlot, ItemStack.EMPTY);
// drop core
final ItemStack extraB = ia.addItems(this.component.stack(1));
if (!extraB.isEmpty()) {
player.dropItem(extraB, false);
}
// drop upgrades
final FixedItemInv upgradesInventory = this.getUpgradesInventory(stack);
for (int upgradeIndex = 0; upgradeIndex < upgradesInventory.getSlotCount(); upgradeIndex++) {
final ItemStack upgradeStack = upgradesInventory.getInvStack(upgradeIndex);
final ItemStack leftStack = ia.addItems(upgradeStack);
if (!leftStack.isEmpty() && upgradeStack.getItem() instanceof IUpgradeModule) {
player.dropItem(upgradeStack, false);
}
}
// drop empty storage cell case
this.dropEmptyStorageCellCase(ia, player);
if (player.currentScreenHandler != null) {
player.currentScreenHandler.sendContentUpdates();
}
return true;
}
}
}
return false;
}
protected abstract void dropEmptyStorageCellCase(final InventoryAdaptor ia, final PlayerEntity player);
@Override
public ActionResult onItemUseFirst(ItemStack stack, ItemUsageContext context) {
return this.disassembleDrive(stack, context.getWorld(), context.getPlayer()) ? ActionResult.SUCCESS
: ActionResult.PASS;
}
// FIXME FABRIC: Handle this in the disassemble recipe
// FIXME FABRIC @Override
// FIXME FABRIC public ItemStack getRecipeRemainder(final ItemStack itemStack) {
// FIXME FABRIC return AEApi.instance().definitions().materials().emptyStorageCell().maybeStack(1)
// FIXME FABRIC .orElseThrow(() -> new MissingDefinitionException(
// FIXME FABRIC "Tried to use empty storage cells while basic storage cells are defined."));
// FIXME FABRIC }
// FIXME FABRIC
// FIXME FABRIC @Override
// FIXME FABRIC public boolean hasRecipeRemainder(final ItemStack stack) {
// FIXME FABRIC return AEConfig.instance().isFeatureEnabled(AEFeature.ENABLE_DISASSEMBLY_CRAFTING);
// FIXME FABRIC }
}
@@ -0,0 +1,86 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.storage;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import appeng.api.AEApi;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.items.materials.MaterialType;
import appeng.util.InventoryAdaptor;
public final class BasicStorageCellItem extends AbstractStorageCell<IAEItemStack> {
protected final int perType;
protected final double idleDrain;
public BasicStorageCellItem(Settings props, final MaterialType whichCell, final int kilobytes) {
super(props, whichCell, kilobytes);
switch (whichCell) {
case ITEM_1K_CELL_COMPONENT:
this.idleDrain = 0.5;
this.perType = 8;
break;
case ITEM_4K_CELL_COMPONENT:
this.idleDrain = 1.0;
this.perType = 32;
break;
case ITEM_16K_CELL_COMPONENT:
this.idleDrain = 1.5;
this.perType = 128;
break;
case ITEM_64K_CELL_COMPONENT:
this.idleDrain = 2.0;
this.perType = 512;
break;
default:
this.idleDrain = 0.0;
this.perType = 8;
}
}
@Override
public int getBytesPerType(ItemStack cellItem) {
return this.perType;
}
@Override
public double getIdleDrain() {
return this.idleDrain;
}
@Override
public IStorageChannel<IAEItemStack> getChannel() {
return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class);
}
@Override
protected void dropEmptyStorageCellCase(final InventoryAdaptor ia, final PlayerEntity player) {
AEApi.instance().definitions().materials().emptyStorageCell().maybeStack(1).ifPresent(is -> {
final ItemStack extraA = ia.addItems(is);
if (!extraA.isEmpty()) {
player.dropItem(extraA, false);
}
});
}
}
@@ -0,0 +1,138 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.storage;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import net.minecraft.item.ItemStack;
import appeng.api.AEApi;
import appeng.api.config.FuzzyMode;
import appeng.api.config.Upgrades;
import appeng.api.implementations.items.IUpgradeModule;
import appeng.api.storage.cells.ICellWorkbenchItem;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.items.AEBaseItem;
import appeng.items.contents.CellConfig;
import appeng.items.contents.CellUpgrades;
import appeng.util.item.AEItemStack;
import appeng.util.prioritylist.FuzzyPriorityList;
import appeng.util.prioritylist.IPartitionList;
import appeng.util.prioritylist.MergedPriorityList;
import appeng.util.prioritylist.PrecisePriorityList;
public class ViewCellItem extends AEBaseItem implements ICellWorkbenchItem {
public ViewCellItem(Settings properties) {
super(properties);
}
public static IPartitionList<IAEItemStack> createFilter(final ItemStack[] list) {
IPartitionList<IAEItemStack> myPartitionList = null;
final MergedPriorityList<IAEItemStack> myMergedList = new MergedPriorityList<>();
for (final ItemStack currentViewCell : list) {
if (currentViewCell == null) {
continue;
}
if ((currentViewCell.getItem() instanceof ViewCellItem)) {
final IItemList<IAEItemStack> priorityList = AEApi.instance().storage()
.getStorageChannel(IItemStorageChannel.class).createList();
final ICellWorkbenchItem vc = (ICellWorkbenchItem) currentViewCell.getItem();
final FixedItemInv upgrades = vc.getUpgradesInventory(currentViewCell);
final FixedItemInv config = vc.getConfigInventory(currentViewCell);
final FuzzyMode fzMode = vc.getFuzzyMode(currentViewCell);
boolean hasInverter = false;
boolean hasFuzzy = false;
for (int x = 0; x < upgrades.getSlotCount(); x++) {
final ItemStack is = upgrades.getInvStack(x);
if (!is.isEmpty() && is.getItem() instanceof IUpgradeModule) {
final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is);
if (u != null) {
switch (u) {
case FUZZY:
hasFuzzy = true;
break;
case INVERTER:
hasInverter = true;
break;
default:
}
}
}
}
for (int x = 0; x < config.getSlotCount(); x++) {
final ItemStack is = config.getInvStack(x);
if (!is.isEmpty()) {
priorityList.add(AEItemStack.fromItemStack(is));
}
}
if (!priorityList.isEmpty()) {
if (hasFuzzy) {
myMergedList.addNewList(new FuzzyPriorityList<>(priorityList, fzMode), !hasInverter);
} else {
myMergedList.addNewList(new PrecisePriorityList<>(priorityList), !hasInverter);
}
myPartitionList = myMergedList;
}
}
}
return myPartitionList;
}
@Override
public boolean isEditable(final ItemStack is) {
return true;
}
@Override
public FixedItemInv getUpgradesInventory(final ItemStack is) {
return new CellUpgrades(is, 2);
}
@Override
public FixedItemInv getConfigInventory(final ItemStack is) {
return new CellConfig(is);
}
@Override
public FuzzyMode getFuzzyMode(final ItemStack is) {
final String fz = is.getOrCreateTag().getString("FuzzyMode");
try {
return FuzzyMode.valueOf(fz);
} catch (final Throwable t) {
return FuzzyMode.IGNORE_ALL;
}
}
@Override
public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {
is.getOrCreateTag().putString("FuzzyMode", fzMode.name());
}
}
@@ -0,0 +1,177 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools;
import java.util.EnumSet;
import java.util.List;
import com.mojang.authlib.GameProfile;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtHelper;
import net.minecraft.text.MutableText;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.ActionResult;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.Hand;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import appeng.api.config.SecurityPermissions;
import appeng.api.features.IPlayerRegistry;
import appeng.api.implementations.items.IBiometricCard;
import appeng.api.networking.security.ISecurityRegistry;
import appeng.core.localization.GuiText;
import appeng.items.AEBaseItem;
public class BiometricCardItem extends AEBaseItem implements IBiometricCard {
public BiometricCardItem(Settings properties) {
super(properties);
}
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity p, final Hand hand) {
if (p.isInSneakingPose()) {
this.encode(p.getStackInHand(hand), p);
p.swingHand(hand);
return TypedActionResult.success(p.getStackInHand(hand));
}
return TypedActionResult.pass(p.getStackInHand(hand));
}
// FIXME FABRIC: Validate that this actually works about as well as the forge hook does
@Override
public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity target, Hand hand) {
if (target instanceof PlayerEntity && !user.isInSneakingPose()) {
if (user.isCreative()) {
stack = user.getStackInHand(hand);
}
this.encode(stack, (PlayerEntity) target);
user.swingHand(hand);
return ActionResult.SUCCESS;
}
return ActionResult.PASS;
}
@Override
public Text getName(final ItemStack is) {
final GameProfile username = this.getProfile(is);
return username != null ? super.getName(is).copy().append(" - " + username.getName())
: super.getName(is);
}
private void encode(final ItemStack is, final PlayerEntity p) {
final GameProfile username = this.getProfile(is);
if (username != null && username.equals(p.getGameProfile())) {
this.setProfile(is, null);
} else {
this.setProfile(is, p.getGameProfile());
}
}
@Override
public void setProfile(final ItemStack itemStack, final GameProfile profile) {
final CompoundTag tag = itemStack.getOrCreateTag();
if (profile != null) {
final CompoundTag pNBT = new CompoundTag();
NbtHelper.fromGameProfile(pNBT, profile);
tag.put("profile", pNBT);
} else {
tag.remove("profile");
}
}
@Override
public GameProfile getProfile(final ItemStack is) {
final CompoundTag tag = is.getOrCreateTag();
if (tag.contains("profile")) {
return NbtHelper.toGameProfile(tag.getCompound("profile"));
}
return null;
}
@Override
public EnumSet<SecurityPermissions> getPermissions(final ItemStack is) {
final CompoundTag tag = is.getOrCreateTag();
final EnumSet<SecurityPermissions> result = EnumSet.noneOf(SecurityPermissions.class);
for (final SecurityPermissions sp : SecurityPermissions.values()) {
if (tag.getBoolean(sp.name())) {
result.add(sp);
}
}
return result;
}
@Override
public boolean hasPermission(final ItemStack is, final SecurityPermissions permission) {
final CompoundTag tag = is.getOrCreateTag();
return tag.getBoolean(permission.name());
}
@Override
public void removePermission(final ItemStack itemStack, final SecurityPermissions permission) {
final CompoundTag tag = itemStack.getOrCreateTag();
if (tag.contains(permission.name())) {
tag.remove(permission.name());
}
}
@Override
public void addPermission(final ItemStack itemStack, final SecurityPermissions permission) {
final CompoundTag tag = itemStack.getOrCreateTag();
tag.putBoolean(permission.name(), true);
}
@Override
public void registerPermissions(final ISecurityRegistry register, final IPlayerRegistry pr, final ItemStack is) {
register.addPlayer(pr.getID(this.getProfile(is)), this.getPermissions(is));
}
@Override
@Environment(EnvType.CLIENT)
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
final EnumSet<SecurityPermissions> perms = this.getPermissions(stack);
if (perms.isEmpty()) {
lines.add(new TranslatableText(GuiText.NoPermissions.getLocal()));
} else {
MutableText msg = null;
for (final SecurityPermissions sp : perms) {
if (msg == null) {
msg = new TranslatableText(sp.getTranslatedName());
} else {
msg = msg.append(", ").append(new TranslatableText(sp.getTranslatedName()));
}
}
lines.add(msg);
}
}
}
@@ -0,0 +1,194 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools;
import java.util.List;
import net.fabricmc.api.EnvType;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.*;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import net.fabricmc.api.Environment;
import appeng.api.implementations.items.IMemoryCard;
import appeng.api.implementations.items.MemoryCardMessages;
import appeng.api.util.AEColor;
import appeng.core.localization.GuiText;
import appeng.core.localization.PlayerMessages;
import appeng.items.AEBaseItem;
import appeng.util.Platform;
public class MemoryCardItem extends AEBaseItem implements IMemoryCard {
private static final AEColor[] DEFAULT_COLOR_CODE = new AEColor[] { AEColor.TRANSPARENT, AEColor.TRANSPARENT,
AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT, AEColor.TRANSPARENT,
AEColor.TRANSPARENT, };
public MemoryCardItem(Settings properties) {
super(properties);
}
@Override
@Environment(EnvType.CLIENT)
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
String firstLineKey = this.getFirstValidTranslationKey(this.getSettingsName(stack) + ".name",
this.getSettingsName(stack));
lines.add(new TranslatableText(firstLineKey));
final CompoundTag data = this.getData(stack);
if (data.contains("tooltip")) {
String tooltipKey = getFirstValidTranslationKey(data.getString("tooltip") + ".name",
data.getString("tooltip"));
lines.add(new TranslatableText(tooltipKey));
}
if (data.contains("freq")) {
final short freq = data.getShort("freq");
final String freqTooltip = Formatting.BOLD + Platform.p2p().toHexString(freq);
lines.add(new TranslatableText("gui.tooltips.appliedenergistics2.P2PFrequency", freqTooltip));
}
}
/**
* Find the localized string...
*
* @param name possible names for the localized string
*
* @return localized name
*/
private String getFirstValidTranslationKey(final String... name) {
for (final String n : name) {
if (Language.getInstance().hasTranslation(n)) {
return n;
}
}
for (final String n : name) {
return n;
}
return "";
}
@Override
public void setMemoryCardContents(final ItemStack is, final String settingsName, final CompoundTag data) {
final CompoundTag c = is.getOrCreateTag();
c.putString("Config", settingsName);
c.put("Data", data);
}
@Override
public String getSettingsName(final ItemStack is) {
final CompoundTag c = is.getOrCreateTag();
final String name = c.getString("Config");
return name.isEmpty() ? GuiText.Blank.getTranslationKey() : name;
}
@Override
public CompoundTag getData(final ItemStack is) {
final CompoundTag c = is.getOrCreateTag();
CompoundTag o = c.getCompound("Data");
return o.copy();
}
@Override
public AEColor[] getColorCode(ItemStack is) {
final CompoundTag tag = this.getData(is);
if (tag.contains("colorCode")) {
final int[] frequency = tag.getIntArray("colorCode");
final AEColor[] colorArray = AEColor.values();
return new AEColor[] { colorArray[frequency[0]], colorArray[frequency[1]], colorArray[frequency[2]],
colorArray[frequency[3]], colorArray[frequency[4]], colorArray[frequency[5]],
colorArray[frequency[6]], colorArray[frequency[7]], };
}
return DEFAULT_COLOR_CODE;
}
@Override
public void notifyUser(final PlayerEntity player, final MemoryCardMessages msg) {
if (Platform.isClient()) {
return;
}
switch (msg) {
case SETTINGS_CLEARED:
player.sendSystemMessage(PlayerMessages.SettingCleared.get(), Util.NIL_UUID);
break;
case INVALID_MACHINE:
player.sendSystemMessage(PlayerMessages.InvalidMachine.get(), Util.NIL_UUID);
break;
case SETTINGS_LOADED:
player.sendSystemMessage(PlayerMessages.LoadedSettings.get(), Util.NIL_UUID);
break;
case SETTINGS_SAVED:
player.sendSystemMessage(PlayerMessages.SavedSettings.get(), Util.NIL_UUID);
break;
case SETTINGS_RESET:
player.sendSystemMessage(PlayerMessages.ResetSettings.get(), Util.NIL_UUID);
break;
default:
}
}
@Override
public ActionResult useOnBlock(ItemUsageContext context) {
if (context.getPlayer().isInSneakingPose()) {
if (!context.getPlayer().world.isClient) {
this.clearCard(context.getPlayer(), context.getWorld(), context.getHand());
}
return ActionResult.SUCCESS;
} else {
return super.useOnBlock(context);
}
}
@Override
public TypedActionResult<ItemStack> use(World w, PlayerEntity player, Hand hand) {
if (player.isInSneakingPose()) {
if (!w.isClient) {
this.clearCard(player, w, hand);
}
}
return super.use(w, player, hand);
}
// FIXME FABRIC probably needs a custom mixin
// FIXME FABRIC @Override
// FIXME FABRIC public boolean doesSneakBypassUse(ItemStack stack, WorldView world, BlockPos pos, PlayerEntity player) {
// FIXME FABRIC return true;
// FIXME FABRIC }
private void clearCard(final PlayerEntity player, final World w, final Hand hand) {
final IMemoryCard mem = (IMemoryCard) player.getStackInHand(hand).getItem();
mem.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED);
player.getStackInHand(hand).setTag(null);
}
}
@@ -0,0 +1,169 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools;
import appeng.hooks.AEToolItem;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.util.*;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.hit.HitResult;
import net.minecraft.world.World;
import appeng.api.implementations.guiobjects.IGuiItem;
import appeng.api.implementations.guiobjects.IGuiItemObject;
import appeng.api.implementations.items.IAEWrench;
import appeng.api.networking.IGridHost;
import appeng.api.parts.IPartHost;
import appeng.api.parts.SelectedPart;
import appeng.api.util.DimensionalCoord;
import appeng.api.util.INetworkToolAgent;
import appeng.container.AEBaseContainer;
import appeng.container.ContainerLocator;
import appeng.container.ContainerOpener;
import appeng.container.implementations.NetworkStatusContainer;
import appeng.container.implementations.NetworkToolContainer;
import appeng.core.AppEng;
import appeng.core.sync.network.NetworkHandler;
import appeng.core.sync.packets.ClickPacket;
import appeng.items.AEBaseItem;
import appeng.items.contents.NetworkToolViewer;
import appeng.util.Platform;
public class NetworkToolItem extends AEBaseItem implements IGuiItem, IAEWrench, AEToolItem {
public NetworkToolItem(Settings properties) {
super(properties);
}
@Override
public IGuiItemObject getGuiObject(final ItemStack is, int playerInventorySlot, final World world,
final BlockPos pos) {
if (pos == null) {
return new NetworkToolViewer(is, null);
}
final BlockEntity te = world.getBlockEntity(pos);
return new NetworkToolViewer(is, (IGridHost) (te instanceof IGridHost ? te : null));
}
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity p, final Hand hand) {
if (Platform.isClient()) {
final HitResult mop = AppEng.instance().getRTR();
if (mop == null || mop.getType() == HitResult.Type.MISS) {
NetworkHandler.instance().sendToServer(new ClickPacket(hand));
}
}
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
}
@Override
public ActionResult onItemUseFirst(ItemStack stack, ItemUsageContext context) {
final BlockHitResult mop = new BlockHitResult(context.getHitPos(), context.getSide(),
context.getBlockPos(), context.hitsInsideBlock());
final BlockEntity te = context.getWorld().getBlockEntity(context.getBlockPos());
if (te instanceof IPartHost) {
final SelectedPart part = ((IPartHost) te).selectPart(mop.getPos());
if (part.part != null || part.facade != null) {
if (part.part instanceof INetworkToolAgent && !((INetworkToolAgent) part.part).showNetworkInfo(mop)) {
return ActionResult.FAIL;
} else if (context.getPlayer().isInSneakingPose()) {
return ActionResult.PASS;
}
}
} else if (te instanceof INetworkToolAgent && !((INetworkToolAgent) te).showNetworkInfo(mop)) {
return ActionResult.FAIL;
}
if (Platform.isClient()) {
NetworkHandler.instance().sendToServer(new ClickPacket(context));
}
return ActionResult.SUCCESS;
}
// FIXME FABRIC: No direct equivalent
// FIXME FABRIC @Override
// FIXME FABRIC public boolean doesSneakBypassUse(ItemStack stack, WorldView world, BlockPos pos, PlayerEntity player) {
// FIXME FABRIC return true;
// FIXME FABRIC }
public boolean serverSideToolLogic(ItemUsageContext useContext) {
BlockPos pos = useContext.getBlockPos();
PlayerEntity p = useContext.getPlayer();
World w = p.world;
Hand hand = useContext.getHand();
Direction side = useContext.getSide();
if (!Platform.hasPermissions(new DimensionalCoord(w, pos), p)) {
return false;
}
final BlockState bs = w.getBlockState(pos);
if (!p.isInSneakingPose()) {
final BlockEntity te = w.getBlockEntity(pos);
if (!(te instanceof IGridHost)) {
BlockState rotatedState = bs.rotate(BlockRotation.CLOCKWISE_90);
if (rotatedState != bs) {
w.setBlockState(pos, rotatedState, 3);
bs.neighborUpdate(w, pos, Blocks.AIR, pos, false);
p.swingHand(hand);
return !w.isClient;
}
}
}
if (!p.isInSneakingPose()) {
if (p.currentScreenHandler instanceof AEBaseContainer) {
return true;
}
final BlockEntity te = w.getBlockEntity(pos);
if (te instanceof IGridHost) {
ContainerOpener.openContainer(NetworkStatusContainer.TYPE, p,
ContainerLocator.forItemUseContext(useContext));
} else {
ContainerOpener.openContainer(NetworkToolContainer.TYPE, p, ContainerLocator.forHand(p, hand));
}
return true;
} else {
BlockHitResult rtr = new BlockHitResult(useContext.getHitPos(), side, pos, false);
bs.onUse(w, p, hand, rtr);
}
return false;
}
@Override
public boolean canWrench(final ItemStack wrench, final PlayerEntity player, final BlockPos pos) {
return true;
}
}
@@ -0,0 +1,167 @@
package appeng.items.tools.powered;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.EnumHashBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import appeng.api.util.AEColor;
/**
* Allows recoloring a variety of vanilla blocks.
*/
public final class BlockRecolorer {
private BlockRecolorer() {
}
private static final BiMap<AEColor, Block> STAINED_GLASS_BY_COLOR = EnumHashBiMap.create(ImmutableMap
.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_STAINED_GLASS)
.put(AEColor.ORANGE, Blocks.ORANGE_STAINED_GLASS).put(AEColor.MAGENTA, Blocks.MAGENTA_STAINED_GLASS)
.put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_STAINED_GLASS).put(AEColor.YELLOW, Blocks.YELLOW_STAINED_GLASS)
.put(AEColor.LIME, Blocks.LIME_STAINED_GLASS).put(AEColor.PINK, Blocks.PINK_STAINED_GLASS)
.put(AEColor.GRAY, Blocks.GRAY_STAINED_GLASS).put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_STAINED_GLASS)
.put(AEColor.CYAN, Blocks.CYAN_STAINED_GLASS).put(AEColor.PURPLE, Blocks.PURPLE_STAINED_GLASS)
.put(AEColor.BLUE, Blocks.BLUE_STAINED_GLASS).put(AEColor.BROWN, Blocks.BROWN_STAINED_GLASS)
.put(AEColor.GREEN, Blocks.GREEN_STAINED_GLASS).put(AEColor.RED, Blocks.RED_STAINED_GLASS)
.put(AEColor.BLACK, Blocks.BLACK_STAINED_GLASS).build());
private static final BiMap<AEColor, Block> STAINED_GLASS_PANE_BY_COLOR = EnumHashBiMap.create(ImmutableMap
.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_STAINED_GLASS_PANE)
.put(AEColor.ORANGE, Blocks.ORANGE_STAINED_GLASS_PANE)
.put(AEColor.MAGENTA, Blocks.MAGENTA_STAINED_GLASS_PANE)
.put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_STAINED_GLASS_PANE)
.put(AEColor.YELLOW, Blocks.YELLOW_STAINED_GLASS_PANE).put(AEColor.LIME, Blocks.LIME_STAINED_GLASS_PANE)
.put(AEColor.PINK, Blocks.PINK_STAINED_GLASS_PANE).put(AEColor.GRAY, Blocks.GRAY_STAINED_GLASS_PANE)
.put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_STAINED_GLASS_PANE)
.put(AEColor.CYAN, Blocks.CYAN_STAINED_GLASS_PANE).put(AEColor.PURPLE, Blocks.PURPLE_STAINED_GLASS_PANE)
.put(AEColor.BLUE, Blocks.BLUE_STAINED_GLASS_PANE).put(AEColor.BROWN, Blocks.BROWN_STAINED_GLASS_PANE)
.put(AEColor.GREEN, Blocks.GREEN_STAINED_GLASS_PANE).put(AEColor.RED, Blocks.RED_STAINED_GLASS_PANE)
.put(AEColor.BLACK, Blocks.BLACK_STAINED_GLASS_PANE).build());
private static final BiMap<AEColor, Block> WOOL_BY_COLOR = EnumHashBiMap.create(ImmutableMap
.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_WOOL).put(AEColor.ORANGE, Blocks.ORANGE_WOOL)
.put(AEColor.MAGENTA, Blocks.MAGENTA_WOOL).put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_WOOL)
.put(AEColor.YELLOW, Blocks.YELLOW_WOOL).put(AEColor.LIME, Blocks.LIME_WOOL)
.put(AEColor.PINK, Blocks.PINK_WOOL).put(AEColor.GRAY, Blocks.GRAY_WOOL)
.put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_WOOL).put(AEColor.CYAN, Blocks.CYAN_WOOL)
.put(AEColor.PURPLE, Blocks.PURPLE_WOOL).put(AEColor.BLUE, Blocks.BLUE_WOOL)
.put(AEColor.BROWN, Blocks.BROWN_WOOL).put(AEColor.GREEN, Blocks.GREEN_WOOL)
.put(AEColor.RED, Blocks.RED_WOOL).put(AEColor.BLACK, Blocks.BLACK_WOOL).build());
private static final BiMap<AEColor, Block> BANNER_BY_COLOR = EnumHashBiMap.create(ImmutableMap
.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_BANNER).put(AEColor.ORANGE, Blocks.ORANGE_BANNER)
.put(AEColor.MAGENTA, Blocks.MAGENTA_BANNER).put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_BANNER)
.put(AEColor.YELLOW, Blocks.YELLOW_BANNER).put(AEColor.LIME, Blocks.LIME_BANNER)
.put(AEColor.PINK, Blocks.PINK_BANNER).put(AEColor.GRAY, Blocks.GRAY_BANNER)
.put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_BANNER).put(AEColor.CYAN, Blocks.CYAN_BANNER)
.put(AEColor.PURPLE, Blocks.PURPLE_BANNER).put(AEColor.BLUE, Blocks.BLUE_BANNER)
.put(AEColor.BROWN, Blocks.BROWN_BANNER).put(AEColor.GREEN, Blocks.GREEN_BANNER)
.put(AEColor.RED, Blocks.RED_BANNER).put(AEColor.BLACK, Blocks.BLACK_BANNER).build());
private static final BiMap<AEColor, Block> WALL_BANNER_BY_COLOR = EnumHashBiMap
.create(ImmutableMap.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_WALL_BANNER)
.put(AEColor.ORANGE, Blocks.ORANGE_WALL_BANNER).put(AEColor.MAGENTA, Blocks.MAGENTA_WALL_BANNER)
.put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_WALL_BANNER)
.put(AEColor.YELLOW, Blocks.YELLOW_WALL_BANNER).put(AEColor.LIME, Blocks.LIME_WALL_BANNER)
.put(AEColor.PINK, Blocks.PINK_WALL_BANNER).put(AEColor.GRAY, Blocks.GRAY_WALL_BANNER)
.put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_WALL_BANNER).put(AEColor.CYAN, Blocks.CYAN_WALL_BANNER)
.put(AEColor.PURPLE, Blocks.PURPLE_WALL_BANNER).put(AEColor.BLUE, Blocks.BLUE_WALL_BANNER)
.put(AEColor.BROWN, Blocks.BROWN_WALL_BANNER).put(AEColor.GREEN, Blocks.GREEN_WALL_BANNER)
.put(AEColor.RED, Blocks.RED_WALL_BANNER).put(AEColor.BLACK, Blocks.BLACK_WALL_BANNER).build());
private static final BiMap<AEColor, Block> CARPET_BY_COLOR = EnumHashBiMap.create(ImmutableMap
.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_CARPET).put(AEColor.ORANGE, Blocks.ORANGE_CARPET)
.put(AEColor.MAGENTA, Blocks.MAGENTA_CARPET).put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_CARPET)
.put(AEColor.YELLOW, Blocks.YELLOW_CARPET).put(AEColor.LIME, Blocks.LIME_CARPET)
.put(AEColor.PINK, Blocks.PINK_CARPET).put(AEColor.GRAY, Blocks.GRAY_CARPET)
.put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_CARPET).put(AEColor.CYAN, Blocks.CYAN_CARPET)
.put(AEColor.PURPLE, Blocks.PURPLE_CARPET).put(AEColor.BLUE, Blocks.BLUE_CARPET)
.put(AEColor.BROWN, Blocks.BROWN_CARPET).put(AEColor.GREEN, Blocks.GREEN_CARPET)
.put(AEColor.RED, Blocks.RED_CARPET).put(AEColor.BLACK, Blocks.BLACK_CARPET).build());
private static final BiMap<AEColor, Block> TERRACOTTA_BY_COLOR = EnumHashBiMap
.create(ImmutableMap.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_TERRACOTTA)
.put(AEColor.ORANGE, Blocks.ORANGE_TERRACOTTA).put(AEColor.MAGENTA, Blocks.MAGENTA_TERRACOTTA)
.put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_TERRACOTTA).put(AEColor.YELLOW, Blocks.YELLOW_TERRACOTTA)
.put(AEColor.LIME, Blocks.LIME_TERRACOTTA).put(AEColor.PINK, Blocks.PINK_TERRACOTTA)
.put(AEColor.GRAY, Blocks.GRAY_TERRACOTTA).put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_TERRACOTTA)
.put(AEColor.CYAN, Blocks.CYAN_TERRACOTTA).put(AEColor.PURPLE, Blocks.PURPLE_TERRACOTTA)
.put(AEColor.BLUE, Blocks.BLUE_TERRACOTTA).put(AEColor.BROWN, Blocks.BROWN_TERRACOTTA)
.put(AEColor.GREEN, Blocks.GREEN_TERRACOTTA).put(AEColor.RED, Blocks.RED_TERRACOTTA)
.put(AEColor.BLACK, Blocks.BLACK_TERRACOTTA).build());
private static final BiMap<AEColor, Block> GLAZED_TERRACOTTA_BY_COLOR = EnumHashBiMap.create(ImmutableMap
.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_GLAZED_TERRACOTTA)
.put(AEColor.ORANGE, Blocks.ORANGE_GLAZED_TERRACOTTA).put(AEColor.MAGENTA, Blocks.MAGENTA_GLAZED_TERRACOTTA)
.put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_GLAZED_TERRACOTTA)
.put(AEColor.YELLOW, Blocks.YELLOW_GLAZED_TERRACOTTA).put(AEColor.LIME, Blocks.LIME_GLAZED_TERRACOTTA)
.put(AEColor.PINK, Blocks.PINK_GLAZED_TERRACOTTA).put(AEColor.GRAY, Blocks.GRAY_GLAZED_TERRACOTTA)
.put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_GLAZED_TERRACOTTA)
.put(AEColor.CYAN, Blocks.CYAN_GLAZED_TERRACOTTA).put(AEColor.PURPLE, Blocks.PURPLE_GLAZED_TERRACOTTA)
.put(AEColor.BLUE, Blocks.BLUE_GLAZED_TERRACOTTA).put(AEColor.BROWN, Blocks.BROWN_GLAZED_TERRACOTTA)
.put(AEColor.GREEN, Blocks.GREEN_GLAZED_TERRACOTTA).put(AEColor.RED, Blocks.RED_GLAZED_TERRACOTTA)
.put(AEColor.BLACK, Blocks.BLACK_GLAZED_TERRACOTTA).build());
private static final BiMap<AEColor, Block> CONCRETE_BY_COLOR = EnumHashBiMap
.create(ImmutableMap.<AEColor, Block>builder().put(AEColor.WHITE, Blocks.WHITE_CONCRETE)
.put(AEColor.ORANGE, Blocks.ORANGE_CONCRETE).put(AEColor.MAGENTA, Blocks.MAGENTA_CONCRETE)
.put(AEColor.LIGHT_BLUE, Blocks.LIGHT_BLUE_CONCRETE).put(AEColor.YELLOW, Blocks.YELLOW_CONCRETE)
.put(AEColor.LIME, Blocks.LIME_CONCRETE).put(AEColor.PINK, Blocks.PINK_CONCRETE)
.put(AEColor.GRAY, Blocks.GRAY_CONCRETE).put(AEColor.LIGHT_GRAY, Blocks.LIGHT_GRAY_CONCRETE)
.put(AEColor.CYAN, Blocks.CYAN_CONCRETE).put(AEColor.PURPLE, Blocks.PURPLE_CONCRETE)
.put(AEColor.BLUE, Blocks.BLUE_CONCRETE).put(AEColor.BROWN, Blocks.BROWN_CONCRETE)
.put(AEColor.GREEN, Blocks.GREEN_CONCRETE).put(AEColor.RED, Blocks.RED_CONCRETE)
.put(AEColor.BLACK, Blocks.BLACK_CONCRETE).build());
private static final List<RecolorableBlockGroup> BLOCK_GROUPS = ImmutableList.of(
new RecolorableBlockGroup(Blocks.GLASS, STAINED_GLASS_BY_COLOR),
new RecolorableBlockGroup(Blocks.GLASS_PANE, STAINED_GLASS_PANE_BY_COLOR),
new RecolorableBlockGroup(Blocks.WHITE_WOOL, WOOL_BY_COLOR),
new RecolorableBlockGroup(Blocks.WHITE_BANNER, BANNER_BY_COLOR),
new RecolorableBlockGroup(Blocks.WHITE_WALL_BANNER, WALL_BANNER_BY_COLOR),
new RecolorableBlockGroup(Blocks.WHITE_CARPET, CARPET_BY_COLOR),
new RecolorableBlockGroup(Blocks.TERRACOTTA, TERRACOTTA_BY_COLOR),
new RecolorableBlockGroup(null, GLAZED_TERRACOTTA_BY_COLOR),
new RecolorableBlockGroup(null, CONCRETE_BY_COLOR));
public static Block recolor(Block block, AEColor newColor) {
Preconditions.checkNotNull(block);
for (RecolorableBlockGroup group : BLOCK_GROUPS) {
if (group.uncoloredVariant == block || group.coloredVariants.containsValue(block)) {
Block newBlock = group.coloredVariants.get(newColor);
if (newBlock == null) {
if (group.uncoloredVariant != null) {
newBlock = group.uncoloredVariant;
} else {
newBlock = block;
}
}
return newBlock;
}
}
return block;
}
private static class RecolorableBlockGroup {
final Block uncoloredVariant;
final BiMap<AEColor, Block> coloredVariants;
public RecolorableBlockGroup(Block uncoloredVariant, BiMap<AEColor, Block> coloredVariants) {
this.uncoloredVariant = uncoloredVariant;
this.coloredVariants = coloredVariants;
}
}
}
@@ -0,0 +1,60 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools.powered;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.util.math.Box;
import appeng.api.config.Actionable;
import appeng.core.AEConfig;
import appeng.core.AppEng;
import appeng.core.sync.packets.LightningPacket;
import appeng.items.tools.powered.powersink.AEBasePoweredItem;
import appeng.util.Platform;
public class ChargedStaffItem extends AEBasePoweredItem {
public ChargedStaffItem(Item.Settings props) {
super(AEConfig.instance().getChargedStaffBattery(), props);
}
@Override
public boolean postHit(final ItemStack item, final LivingEntity target, final LivingEntity hitter) {
if (this.getAECurrentPower(item) > 300) {
this.extractAEPower(item, 300, Actionable.MODULATE);
if (Platform.isServer()) {
for (int x = 0; x < 2; x++) {
final Box entityBoundingBox = target.getBoundingBox();
final float dx = (float) (Platform.getRandomFloat() * target.getWidth() + entityBoundingBox.minX);
final float dy = (float) (Platform.getRandomFloat() * target.getHeight() + entityBoundingBox.minY);
final float dz = (float) (Platform.getRandomFloat() * target.getWidth() + entityBoundingBox.minZ);
AppEng.instance().sendToAllNearExcept(null, dx, dy, dz, 32.0, target.world,
new LightningPacket(dx, dy, dz));
}
}
target.damage(DamageSource.MAGIC, 6);
return true;
}
return false;
}
}
@@ -0,0 +1,465 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools.powered;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.FuzzyMode;
import appeng.api.implementations.items.IStorageCell;
import appeng.api.implementations.tiles.IColorableTile;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.cells.ICellInventoryHandler;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AEColor;
import appeng.api.util.DimensionalCoord;
import appeng.block.networking.CableBusBlock;
import appeng.block.paint.PaintSplotchesBlock;
import appeng.core.AEConfig;
import appeng.core.AppEng;
import appeng.core.localization.GuiText;
import appeng.helpers.IMouseWheelItem;
import appeng.hooks.IBlockTool;
import appeng.items.contents.CellConfig;
import appeng.items.contents.CellUpgrades;
import appeng.items.misc.PaintBallItem;
import appeng.items.tools.powered.powersink.AEBasePoweredItem;
import appeng.me.helpers.BaseActionSource;
import appeng.tile.misc.PaintSplotchesBlockEntity;
import appeng.util.FakePlayer;
import appeng.util.Platform;
import appeng.util.item.AEItemStack;
import com.google.common.collect.ImmutableMap;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.object.builder.v1.client.model.FabricModelPredicateProviderRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.item.SnowballItem;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.state.property.Property;
import net.minecraft.tag.ItemTags;
import net.minecraft.tag.Tag;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.World;
import javax.annotation.Nullable;
import java.util.*;
public class ColorApplicatorItem extends AEBasePoweredItem
implements IStorageCell<IAEItemStack>, IBlockTool, IMouseWheelItem {
private static final Map<Identifier, AEColor> TAG_TO_COLOR = ImmutableMap.<Identifier, AEColor>builder()
.put(new Identifier("forge:dyes/black"), AEColor.BLACK)
.put(new Identifier("forge:dyes/blue"), AEColor.BLUE)
.put(new Identifier("forge:dyes/brown"), AEColor.BROWN)
.put(new Identifier("forge:dyes/cyan"), AEColor.CYAN)
.put(new Identifier("forge:dyes/gray"), AEColor.GRAY)
.put(new Identifier("forge:dyes/green"), AEColor.GREEN)
.put(new Identifier("forge:dyes/light_blue"), AEColor.LIGHT_BLUE)
.put(new Identifier("forge:dyes/light_gray"), AEColor.LIGHT_GRAY)
.put(new Identifier("forge:dyes/lime"), AEColor.LIME)
.put(new Identifier("forge:dyes/magenta"), AEColor.MAGENTA)
.put(new Identifier("forge:dyes/orange"), AEColor.ORANGE)
.put(new Identifier("forge:dyes/pink"), AEColor.PINK)
.put(new Identifier("forge:dyes/purple"), AEColor.PURPLE)
.put(new Identifier("forge:dyes/red"), AEColor.RED)
.put(new Identifier("forge:dyes/white"), AEColor.WHITE)
.put(new Identifier("forge:dyes/yellow"), AEColor.YELLOW).build();
private static final String TAG_COLOR = "color";
public ColorApplicatorItem(Item.Settings props) {
super(AEConfig.instance().getColorApplicatorBattery(), props);
FabricModelPredicateProviderRegistry.register(
this,
new Identifier(AppEng.MOD_ID, "colored"),
(itemStack, world, entity) -> {
// If the stack has no color, don't use the colored model since the impact of
// calling getColor for every quad is extremely high, if the stack tries to
// re-search its
// inventory for a new paintball everytime
AEColor col = getActiveColor(itemStack);
return (col != null) ? 1 : 0;
}
);
}
@Override
public ActionResult onItemUse(ItemUsageContext context) {
World w = context.getWorld();
BlockPos pos = context.getBlockPos();
ItemStack is = context.getStack();
Direction side = context.getSide();
PlayerEntity p = context.getPlayer(); // This can be null
if (p == null && w instanceof ServerWorld) {
p = FakePlayer.getOrCreate((ServerWorld) w);
}
final Block blk = w.getBlockState(pos).getBlock();
ItemStack paintBall = this.getColor(is);
final IMEInventory<IAEItemStack> inv = AEApi.instance().registries().cell().getCellInventory(is, null,
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
if (inv != null) {
final IAEItemStack option = inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.SIMULATE,
new BaseActionSource());
if (option != null) {
paintBall = option.createItemStack();
paintBall.setCount(1);
} else {
paintBall = ItemStack.EMPTY;
}
if (p != null && !Platform.hasPermissions(new DimensionalCoord(w, pos), p)) {
return ActionResult.FAIL;
}
final double powerPerUse = 100;
if (!paintBall.isEmpty() && paintBall.getItem() instanceof SnowballItem) {
final BlockEntity te = w.getBlockEntity(pos);
// clean cables.
if (te instanceof IColorableTile && p != null) {
if (this.getAECurrentPower(is) > powerPerUse
&& ((IColorableTile) te).getColor() != AEColor.TRANSPARENT) {
if (((IColorableTile) te).recolourBlock(side, AEColor.TRANSPARENT, p)) {
inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.MODULATE,
new BaseActionSource());
this.extractAEPower(is, powerPerUse, Actionable.MODULATE);
return ActionResult.SUCCESS;
}
}
}
// clean paint balls..
final Block testBlk = w.getBlockState(pos.offset(side)).getBlock();
final BlockEntity painted = w.getBlockEntity(pos.offset(side));
if (this.getAECurrentPower(is) > powerPerUse && testBlk instanceof PaintSplotchesBlock
&& painted instanceof PaintSplotchesBlockEntity) {
inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.MODULATE, new BaseActionSource());
this.extractAEPower(is, powerPerUse, Actionable.MODULATE);
((PaintSplotchesBlockEntity) painted).cleanSide(side.getOpposite());
return ActionResult.SUCCESS;
}
} else if (!paintBall.isEmpty()) {
final AEColor color = this.getColorFromItem(paintBall);
if (color != null && this.getAECurrentPower(is) > powerPerUse) {
if (color != AEColor.TRANSPARENT && this.recolourBlock(blk, side, w, pos, color, p)) {
inv.extractItems(AEItemStack.fromItemStack(paintBall), Actionable.MODULATE,
new BaseActionSource());
this.extractAEPower(is, powerPerUse, Actionable.MODULATE);
return ActionResult.SUCCESS;
}
}
}
}
if (p != null && p.isInSneakingPose()) {
this.cycleColors(is, paintBall, 1);
}
return ActionResult.FAIL;
}
@Override
public Text getName(final ItemStack is) {
Text extra = GuiText.Empty.textComponent();
final AEColor selected = this.getActiveColor(is);
if (selected != null && Platform.isClient()) {
extra = new TranslatableText(selected.translationKey);
}
return super.getName(is).copy().append(" - ").append(extra);
}
public AEColor getActiveColor(final ItemStack tol) {
return this.getColorFromItem(this.getColor(tol));
}
private AEColor getColorFromItem(final ItemStack paintBall) {
if (paintBall.isEmpty()) {
return null;
}
if (paintBall.getItem() instanceof SnowballItem) {
return AEColor.TRANSPARENT;
}
if (paintBall.getItem() instanceof PaintBallItem) {
final PaintBallItem ipb = (PaintBallItem) paintBall.getItem();
return ipb.getColor();
} else {
for (Map.Entry<Identifier, AEColor> entry : TAG_TO_COLOR.entrySet()) {
Tag<Item> tag = ItemTags.getContainer().get(entry.getKey());
if (tag != null && paintBall.getItem().isIn(tag)) {
return entry.getValue();
}
}
}
return null;
}
public ItemStack getColor(final ItemStack is) {
final CompoundTag c = is.getTag();
if (c != null && c.contains(TAG_COLOR)) {
final CompoundTag color = c.getCompound(TAG_COLOR);
final ItemStack oldColor = ItemStack.fromTag(color);
if (!oldColor.isEmpty()) {
return oldColor;
}
}
return this.findNextColor(is, ItemStack.EMPTY, 0);
}
private ItemStack findNextColor(final ItemStack is, final ItemStack anchor, final int scrollOffset) {
ItemStack newColor = ItemStack.EMPTY;
final IMEInventory<IAEItemStack> inv = AEApi.instance().registries().cell().getCellInventory(is, null,
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
if (inv != null) {
final IItemList<IAEItemStack> itemList = inv.getAvailableItems(
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList());
if (anchor.isEmpty()) {
final IAEItemStack firstItem = itemList.getFirstItem();
if (firstItem != null) {
newColor = firstItem.asItemStackRepresentation();
}
} else {
final LinkedList<IAEItemStack> list = new LinkedList<>();
for (final IAEItemStack i : itemList) {
list.add(i);
}
if (list.isEmpty()) {
return ItemStack.EMPTY;
}
// Sort by color
list.sort(Comparator.comparingInt(a -> {
AEColor color = getColorFromItem(a.getDefinition());
return color != null ? color.ordinal() : Integer.MAX_VALUE;
}));
IAEItemStack where = list.getFirst();
int cycles = 1 + list.size();
AEColor anchorColor = getColorFromItem(anchor);
while (cycles > 0 && getColorFromItem(where.getDefinition()) != anchorColor) {
list.addLast(list.removeFirst());
cycles--;
where = list.getFirst();
}
if (scrollOffset > 0) {
list.addLast(list.removeFirst());
}
if (scrollOffset < 0) {
list.addFirst(list.removeLast());
}
return list.get(0).asItemStackRepresentation();
}
}
if (!newColor.isEmpty()) {
this.setColor(is, newColor);
}
return newColor;
}
private void setColor(final ItemStack is, final ItemStack newColor) {
final CompoundTag data = is.getOrCreateTag();
if (newColor.isEmpty()) {
data.remove(TAG_COLOR);
} else {
final CompoundTag color = new CompoundTag();
newColor.toTag(color);
data.put(TAG_COLOR, color);
}
}
private boolean recolourBlock(final Block blk, final Direction side, final World w, final BlockPos pos,
final AEColor newColor, @Nullable final PlayerEntity p) {
final BlockState state = w.getBlockState(pos);
Block recolored = BlockRecolorer.recolor(blk, newColor);
if (recolored != blk) {
BlockState newState = recolored.getDefaultState();
for (Property<?> prop : newState.getProperties()) {
newState = copyProp(state, newState, prop);
}
return w.setBlockState(pos, newState);
}
BlockEntity be = w.getBlockEntity(pos);
if (be instanceof IColorableTile) {
IColorableTile ct = (IColorableTile) be;
AEColor c = ct.getColor();
if (c != newColor) {
ct.recolourBlock(side, newColor, null);
return true;
}
return false;
}
if (blk instanceof CableBusBlock && p != null) {
return ((CableBusBlock) blk).recolorBlock(w, pos, side, newColor.dye, p);
}
return false;
}
private static <T extends Comparable<T>> BlockState copyProp(BlockState oldState, BlockState newState,
Property<T> prop) {
if (newState.contains(prop)) {
return newState.with(prop, oldState.get(prop));
}
return newState;
}
public void cycleColors(final ItemStack is, final ItemStack paintBall, final int i) {
if (paintBall.isEmpty()) {
this.setColor(is, this.getColor(is));
} else {
this.setColor(is, this.findNextColor(is, paintBall, i));
}
}
@Override
@Environment(EnvType.CLIENT)
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
super.appendTooltip(stack, world, lines, advancedTooltips);
final ICellInventoryHandler<IAEItemStack> cdi = AEApi.instance().registries().cell().getCellInventory(stack,
null, AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
AEApi.instance().client().addCellInformation(cdi, lines);
}
@Override
public int getBytes(final ItemStack cellItem) {
return 512;
}
@Override
public int getBytesPerType(final ItemStack cellItem) {
return 8;
}
@Override
public int getTotalTypes(final ItemStack cellItem) {
return 27;
}
@Override
public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) {
if (requestedAddition != null) {
return getColorFromItem(requestedAddition.getDefinition()) == null;
}
return true;
}
@Override
public boolean storableInStorageCell() {
return true;
}
@Override
public boolean isStorageCell(final ItemStack i) {
return true;
}
@Override
public double getIdleDrain() {
return 0.5;
}
@Override
public IStorageChannel<IAEItemStack> getChannel() {
return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class);
}
@Override
public boolean isEditable(final ItemStack is) {
return true;
}
@Override
public FixedItemInv getUpgradesInventory(final ItemStack is) {
return new CellUpgrades(is, 2);
}
@Override
public FixedItemInv getConfigInventory(final ItemStack is) {
return new CellConfig(is);
}
@Override
public FuzzyMode getFuzzyMode(final ItemStack is) {
final String fz = is.getOrCreateTag().getString("FuzzyMode");
try {
return FuzzyMode.valueOf(fz);
} catch (final Throwable t) {
return FuzzyMode.IGNORE_ALL;
}
}
@Override
public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {
is.getOrCreateTag().putString("FuzzyMode", fzMode.name());
}
@Override
public void onWheel(final ItemStack is, final boolean up) {
this.cycleColors(is, this.getColor(is), up ? 1 : -1);
}
@Override
public boolean canRepair(ItemStack stack, ItemStack ingredient) {
return false;
}
}
@@ -0,0 +1,41 @@
package appeng.items.tools.powered;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.item.ItemStack;
import appeng.api.util.AEColor;
import appeng.bootstrap.IItemRendering;
import appeng.bootstrap.ItemRenderingCustomizer;
public class ColorApplicatorItemRendering extends ItemRenderingCustomizer {
@Override
@Environment(EnvType.CLIENT)
public void customize(IItemRendering rendering) {
rendering.color(this::getColor);
}
private int getColor(ItemStack itemStack, int idx) {
if (idx == 0) {
return -1;
}
final AEColor col = ((ColorApplicatorItem) itemStack.getItem()).getActiveColor(itemStack);
if (col == null) {
return -1;
}
switch (idx) {
case 1:
return col.blackVariant;
case 2:
return col.mediumVariant;
case 3:
return col.whiteVariant;
default:
return -1;
}
}
}
@@ -0,0 +1,342 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools.powered;
import java.util.*;
import appeng.mixins.TntAccessor;
import appeng.util.FakePlayer;
import net.minecraft.block.*;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.Fluids;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.item.*;
import net.minecraft.recipe.RecipeType;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.recipe.SmeltingRecipe;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.state.property.Properties;
import net.minecraft.util.*;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.RayTraceContext;
import net.minecraft.util.hit.HitResult;
import net.minecraft.world.World;
import net.minecraft.server.world.ServerWorld;
import appeng.api.config.Actionable;
import appeng.api.util.DimensionalCoord;
import appeng.block.misc.TinyTNTBlock;
import appeng.container.ContainerNull;
import appeng.core.AEConfig;
import appeng.hooks.IBlockTool;
import appeng.items.tools.powered.powersink.AEBasePoweredItem;
import appeng.util.InWorldToolOperationResult;
import appeng.util.Platform;
public class EntropyManipulatorItem extends AEBasePoweredItem implements IBlockTool {
private final Map<InWorldToolOperationIngredient, InWorldToolOperationResult> heatUp;
private final Map<InWorldToolOperationIngredient, InWorldToolOperationResult> coolDown;
public EntropyManipulatorItem(Item.Settings props) {
super(AEConfig.instance().getEntropyManipulatorBattery(), props);
this.heatUp = new HashMap<>();
this.coolDown = new HashMap<>();
this.coolDown.put(new InWorldToolOperationIngredient(Blocks.STONE),
new InWorldToolOperationResult(Blocks.COBBLESTONE.getDefaultState()));
this.coolDown.put(new InWorldToolOperationIngredient(Blocks.STONE_BRICKS),
new InWorldToolOperationResult(Blocks.CRACKED_STONE_BRICKS.getDefaultState()));
this.coolDown.put(new InWorldToolOperationIngredient(Blocks.LAVA, Fluids.LAVA),
new InWorldToolOperationResult(Blocks.OBSIDIAN.getDefaultState()));
this.coolDown.put(new InWorldToolOperationIngredient(Blocks.LAVA, Fluids.FLOWING_LAVA),
new InWorldToolOperationResult(Blocks.OBSIDIAN.getDefaultState()));
this.coolDown.put(new InWorldToolOperationIngredient(Blocks.GRASS_BLOCK),
new InWorldToolOperationResult(Blocks.DIRT.getDefaultState()));
final List<ItemStack> snowBalls = new ArrayList<>();
snowBalls.add(new ItemStack(Items.SNOWBALL));
this.coolDown.put(new InWorldToolOperationIngredient(Blocks.WATER, Fluids.FLOWING_WATER),
new InWorldToolOperationResult(null, snowBalls));
this.coolDown.put(new InWorldToolOperationIngredient(Blocks.WATER, Fluids.WATER),
new InWorldToolOperationResult(Blocks.ICE.getDefaultState()));
this.heatUp.put(new InWorldToolOperationIngredient(Blocks.ICE),
new InWorldToolOperationResult(Blocks.WATER.getDefaultState()));
this.heatUp.put(new InWorldToolOperationIngredient(Blocks.WATER, Fluids.WATER),
new InWorldToolOperationResult());
this.heatUp.put(new InWorldToolOperationIngredient(Blocks.WATER, Fluids.FLOWING_WATER),
new InWorldToolOperationResult());
this.heatUp.put(new InWorldToolOperationIngredient(Blocks.SNOW), new InWorldToolOperationResult(
Blocks.WATER.getDefaultState().with(Properties.LEVEL_15, 7), Fluids.FLOWING_WATER));
}
private static class InWorldToolOperationIngredient {
private final Block block;
private final Fluid fluid;
public InWorldToolOperationIngredient(Block block) {
this(block, Fluids.EMPTY);
}
public InWorldToolOperationIngredient(Block block, Fluid fluid) {
this.block = block;
this.fluid = fluid;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
InWorldToolOperationIngredient that = (InWorldToolOperationIngredient) o;
return block.equals(that.block) && fluid.equals(that.fluid);
}
@Override
public int hashCode() {
return Objects.hash(block, fluid);
}
}
private void heat(final Block block, Fluid fluid, final World w, final BlockPos pos) {
InWorldToolOperationResult r = this.heatUp.get(new InWorldToolOperationIngredient(block, fluid));
if (r == null) {
// Try with "don't care" fluid
r = this.heatUp.get(new InWorldToolOperationIngredient(block, Fluids.EMPTY));
}
if (r.getBlockState() != null) {
w.setBlockState(pos, r.getBlockState(), 3);
} else {
w.setBlockState(pos, Fluids.EMPTY.getDefaultState().getBlockState(), 3);
}
if (r.getDrops() != null) {
Platform.spawnDrops(w, pos, r.getDrops());
}
if (!w.isClient) {
// Same effect as emptying a water bucket in the nether (see BucketItem)
w.playSound(null, pos, SoundEvents.BLOCK_FIRE_EXTINGUISH, SoundCategory.BLOCKS, 0.5F,
2.6F + (w.random.nextFloat() - w.random.nextFloat()) * 0.8F);
for (int l = 0; l < 8; ++l) {
w.addParticle(ParticleTypes.LARGE_SMOKE, (double) pos.getX() + Math.random(),
(double) pos.getY() + Math.random(), (double) pos.getZ() + Math.random(), 0.0D, 0.0D, 0.0D);
}
}
}
private boolean canHeat(final Block block, Fluid fluid) {
InWorldToolOperationResult r = this.heatUp.get(new InWorldToolOperationIngredient(block, fluid));
if (r == null) {
// Also try with "don't care" fluid
r = this.heatUp.get(new InWorldToolOperationIngredient(block, Fluids.EMPTY));
}
return r != null;
}
private void cool(final Block block, Fluid fluid, final World w, final BlockPos pos) {
InWorldToolOperationResult r = this.coolDown.get(new InWorldToolOperationIngredient(block, fluid));
if (r == null) {
r = this.coolDown.get(new InWorldToolOperationIngredient(block, Fluids.EMPTY));
}
if (r.getBlockState() != null) {
w.setBlockState(pos, r.getBlockState(), 3);
} else {
w.removeBlock(pos, false);
}
if (r.getDrops() != null) {
Platform.spawnDrops(w, pos, r.getDrops());
}
}
private boolean canCool(Block block, Fluid fluid) {
InWorldToolOperationResult r = this.coolDown.get(new InWorldToolOperationIngredient(block, fluid));
if (r == null) {
r = this.coolDown.get(new InWorldToolOperationIngredient(block, Fluids.EMPTY));
}
return r != null;
}
@Override
public boolean postHit(final ItemStack item, final LivingEntity target, final LivingEntity hitter) {
if (this.getAECurrentPower(item) > 1600) {
this.extractAEPower(item, 1600, Actionable.MODULATE);
target.setFireTicks(8);
}
return false;
}
// Overridden to allow use of the item on WATER and LAVA which are otherwise not
// considered for onItemUse
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity p, final Hand hand) {
final BlockHitResult target = rayTrace(w, p, RayTraceContext.FluidHandling.ANY);
if (target.getType() != HitResult.Type.BLOCK) {
BlockPos pos = target.getBlockPos();
final BlockState state = w.getBlockState(pos);
if (state.getMaterial() == Material.LAVA || state.getMaterial() == Material.WATER) {
if (Platform.hasPermissions(new DimensionalCoord(w, pos), p)) {
ItemUsageContext context = new ItemUsageContext(p, hand, target);
this.onItemUse(context);
}
}
}
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
}
@Override
public ActionResult onItemUse(ItemUsageContext context) {
World w = context.getWorld();
ItemStack item = context.getStack();
BlockPos pos = context.getBlockPos();
Direction side = context.getSide();
PlayerEntity p = context.getPlayer();
boolean tryBoth = false;
if (p == null) {
if (w.isClient) {
return ActionResult.FAIL;
}
p = FakePlayer.getOrCreate((ServerWorld) w);
// Fake players cannot crouch and we cannot communicate whether they want to
// heat or cool
tryBoth = true;
}
if (this.getAECurrentPower(item) > 1600) {
if (!p.canPlaceOn(pos, side, item)) {
return ActionResult.FAIL;
}
final Block block = w.getBlockState(pos).getBlock();
final Fluid fluid = w.getFluidState(pos).getFluid();
if (tryBoth || p.isInSneakingPose()) {
if (this.canCool(block, fluid)) {
this.extractAEPower(item, 1600, Actionable.MODULATE);
this.cool(block, fluid, w, pos);
return ActionResult.SUCCESS;
}
}
if (tryBoth || !p.isInSneakingPose()) {
if (block instanceof TntBlock) {
TntAccessor.callPrimeTnt(w, pos, p);
w.removeBlock(pos, false);
return ActionResult.SUCCESS;
}
if (block instanceof TinyTNTBlock) {
w.removeBlock(pos, false);
((TinyTNTBlock) block).startFuse(w, pos, p);
return ActionResult.SUCCESS;
}
if (this.canHeat(block, fluid)) {
this.extractAEPower(item, 1600, Actionable.MODULATE);
this.heat(block, fluid, w, pos);
return ActionResult.SUCCESS;
}
final ItemStack[] stack = Platform.getBlockDrops(w, pos);
final List<ItemStack> out = new ArrayList<>();
boolean hasFurnaceable = false;
boolean canFurnaceable = true;
for (final ItemStack i : stack) {
CraftingInventory tempInv = new CraftingInventory(new ContainerNull(), 1, 1);
tempInv.setStack(0, i);
Optional<SmeltingRecipe> recipe = w.getRecipeManager().getFirstMatch(RecipeType.SMELTING, tempInv, w);
if (recipe.isPresent()) {
ItemStack result = recipe.get().craft(tempInv);
if (result.getItem() instanceof BlockItem) {
// Anti-Dupe-Bug I presume...
if (Block.getBlockFromItem(result.getItem()) == block) {
canFurnaceable = false;
}
}
hasFurnaceable = true;
out.add(result);
} else {
canFurnaceable = false;
out.add(i);
}
}
if (hasFurnaceable && canFurnaceable) {
this.extractAEPower(item, 1600, Actionable.MODULATE);
final InWorldToolOperationResult or = InWorldToolOperationResult
.getBlockOperationResult(out.toArray(new ItemStack[0]));
w.playSound(p, pos.getX() + 0.5D, pos.getY() + 0.5D, pos.getZ() + 0.5D,
SoundEvents.ITEM_FLINTANDSTEEL_USE, SoundCategory.PLAYERS, 1.0F,
RANDOM.nextFloat() * 0.4F + 0.8F);
if (or.getBlockState() == null) {
w.setBlockState(pos, Blocks.AIR.getDefaultState(), 3);
} else {
w.setBlockState(pos, or.getBlockState(), 3);
}
if (or.getDrops() != null) {
Platform.spawnDrops(w, pos, or.getDrops());
}
return ActionResult.SUCCESS;
} else {
final BlockPos offsetPos = pos.offset(side);
if (!p.canPlaceOn(offsetPos, side, item)) {
return ActionResult.FAIL;
}
if (w.isAir(offsetPos)) {
this.extractAEPower(item, 1600, Actionable.MODULATE);
w.playSound(p, offsetPos.getX() + 0.5D, offsetPos.getY() + 0.5D, offsetPos.getZ() + 0.5D,
SoundEvents.ITEM_FLINTANDSTEEL_USE, SoundCategory.PLAYERS, 1.0F,
RANDOM.nextFloat() * 0.4F + 0.8F);
w.setBlockState(offsetPos, Blocks.FIRE.getDefaultState());
}
return ActionResult.SUCCESS;
}
}
}
return ActionResult.PASS;
}
}
@@ -0,0 +1,473 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools.powered;
import java.util.List;
import javax.annotation.Nullable;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import net.fabricmc.api.EnvType;
import net.minecraft.block.BlockState;
import net.minecraft.block.entity.BlockEntity;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.damage.EntityDamageSource;
import net.minecraft.entity.passive.SheepEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Util;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.world.RayTraceContext;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import net.fabricmc.api.Environment;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.FuzzyMode;
import appeng.api.config.Upgrades;
import appeng.api.features.AEFeature;
import appeng.api.implementations.items.IStorageCell;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.cells.ICellInventoryHandler;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AEColor;
import appeng.api.util.DimensionalCoord;
import appeng.core.AEConfig;
import appeng.core.AELog;
import appeng.core.AppEng;
import appeng.core.localization.PlayerMessages;
import appeng.core.sync.network.NetworkHandler;
import appeng.core.sync.packets.MatterCannonPacket;
import appeng.hooks.TickHandler;
import appeng.hooks.TickHandler.PlayerColor;
import appeng.items.contents.CellConfig;
import appeng.items.contents.CellUpgrades;
import appeng.items.misc.PaintBallItem;
import appeng.items.tools.powered.powersink.AEBasePoweredItem;
import appeng.me.helpers.PlayerSource;
import appeng.tile.misc.PaintSplotchesBlockEntity;
import appeng.util.LookDirection;
import appeng.util.Platform;
public class MatterCannonItem extends AEBasePoweredItem implements IStorageCell<IAEItemStack> {
/**
* AE energy units consumer per shot fired.
*/
private static final int ENERGY_PER_SHOT = 1600;
public MatterCannonItem(Item.Settings props) {
super(AEConfig.instance().getMatterCannonBattery(), props);
}
@Environment(EnvType.CLIENT)
@Override
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
super.appendTooltip(stack, world, lines, advancedTooltips);
final ICellInventoryHandler<IAEItemStack> cdi = AEApi.instance().registries().cell().getCellInventory(stack,
null, AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
AEApi.instance().client().addCellInformation(cdi, lines);
}
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity p, final @Nullable Hand hand) {
if (this.getAECurrentPower(p.getStackInHand(hand)) > ENERGY_PER_SHOT) {
int shots = 1;
final CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory(p.getStackInHand(hand));
if (cu != null) {
shots += cu.getInstalledUpgrades(Upgrades.SPEED);
}
final ICellInventoryHandler<IAEItemStack> inv = AEApi.instance().registries().cell().getCellInventory(
p.getStackInHand(hand), null, AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
if (inv != null) {
final IItemList<IAEItemStack> itemList = inv.getAvailableItems(
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class).createList());
IAEItemStack req = itemList.getFirstItem();
if (req instanceof IAEItemStack) {
shots = Math.min(shots, (int) req.getStackSize());
for (int sh = 0; sh < shots; sh++) {
IAEItemStack aeAmmo = req.copy();
this.extractAEPower(p.getStackInHand(hand), ENERGY_PER_SHOT, Actionable.MODULATE);
if (Platform.isClient()) {
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
}
aeAmmo.setStackSize(1);
final ItemStack ammo = aeAmmo.createItemStack();
if (ammo.isEmpty()) {
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
}
aeAmmo = inv.extractItems(aeAmmo, Actionable.MODULATE, new PlayerSource(p, null));
if (aeAmmo == null) {
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
}
final LookDirection dir = Platform.getPlayerRay(p, 32);
final Vec3d rayFrom = dir.getA();
final Vec3d rayTo = dir.getB();
final Vec3d direction = rayTo.subtract(rayFrom);
direction.normalize();
final double d0 = rayFrom.x;
final double d1 = rayFrom.y;
final double d2 = rayFrom.z;
final float penetration = AEApi.instance().registries().matterCannon().getPenetration(ammo); // 196.96655f;
if (penetration <= 0) {
final ItemStack type = aeAmmo.asItemStackRepresentation();
if (type.getItem() instanceof PaintBallItem) {
this.shootPaintBalls(type, w, p, rayFrom, rayTo, direction, d0, d1, d2);
}
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
} else {
this.standardAmmo(penetration, w, p, rayFrom, rayTo, direction, d0, d1, d2);
}
}
} else {
if (Platform.isServer()) {
p.sendSystemMessage(PlayerMessages.AmmoDepleted.get(), Util.NIL_UUID);
}
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
}
}
}
return new TypedActionResult<>(ActionResult.FAIL, p.getStackInHand(hand));
}
private void shootPaintBalls(final ItemStack type, final World w, final PlayerEntity p, final Vec3d Vec3d,
final Vec3d Vec3d1, final Vec3d direction, final double d0, final double d1, final double d2) {
final Box bb = new Box(Math.min(Vec3d.x, Vec3d1.x), Math.min(Vec3d.y, Vec3d1.y),
Math.min(Vec3d.z, Vec3d1.z), Math.max(Vec3d.x, Vec3d1.x), Math.max(Vec3d.y, Vec3d1.y),
Math.max(Vec3d.z, Vec3d1.z)).expand(16, 16, 16);
Entity entity = null;
Vec3d entityIntersection = null;
final List list = w.getEntities(p, bb);
double closest = 9999999.0D;
for (int l = 0; l < list.size(); ++l) {
final Entity entity1 = (Entity) list.get(l);
if (!entity1.isAlive() && entity1 != p && !(entity1 instanceof ItemEntity)) {
if (entity1.isAlive()) {
// prevent killing / flying of mounts.
if (entity1.isConnectedThroughVehicle(p)) {
continue;
}
final float f1 = 0.3F;
final Box boundingBox = entity1.getBoundingBox().expand(f1, f1, f1);
final Vec3d intersection = boundingBox.rayTrace(Vec3d, Vec3d1).orElse(null);
if (intersection != null) {
final double nd = Vec3d.squaredDistanceTo(intersection);
if (nd < closest) {
entity = entity1;
entityIntersection = intersection;
closest = nd;
}
}
}
}
}
RayTraceContext rayTraceContext = new RayTraceContext(Vec3d, Vec3d1, RayTraceContext.ShapeType.COLLIDER,
RayTraceContext.FluidHandling.NONE, p);
HitResult pos = w.rayTrace(rayTraceContext);
final Vec3d vec = new Vec3d(d0, d1, d2);
if (entity != null && pos.getType() != HitResult.Type.MISS
&& pos.getPos().squaredDistanceTo(vec) > closest) {
pos = new EntityHitResult(entity, entityIntersection);
} else if (entity != null && pos.getType() == HitResult.Type.MISS) {
pos = new EntityHitResult(entity, entityIntersection);
}
try {
AppEng.instance().sendToAllNearExcept(null, d0, d1, d2, 128, w,
new MatterCannonPacket(d0, d1, d2, (float) direction.x, (float) direction.y, (float) direction.z,
(byte) (pos.getType() == HitResult.Type.MISS ? 32
: pos.getPos().squaredDistanceTo(vec) + 1)));
} catch (final Exception err) {
AELog.debug(err);
}
if (pos.getType() != HitResult.Type.MISS && type != null && type.getItem() instanceof PaintBallItem) {
final PaintBallItem ipb = (PaintBallItem) type.getItem();
final AEColor col = ipb.getColor();
// boolean lit = ipb.isLumen( type );
if (pos instanceof EntityHitResult) {
EntityHitResult entityResult = (EntityHitResult) pos;
Entity entityHit = entityResult.getEntity();
final int id = entityHit.getEntityId();
final PlayerColor marker = new PlayerColor(id, col, 20 * 30);
TickHandler.INSTANCE.getPlayerColors().put(id, marker);
if (entityHit instanceof SheepEntity) {
final SheepEntity sh = (SheepEntity) entityHit;
sh.setColor(col.dye);
}
entityHit.damage(DamageSource.player(p), 0);
NetworkHandler.instance().sendToAll(marker.getPacket());
} else if (pos instanceof BlockHitResult) {
BlockHitResult blockResult = (BlockHitResult) pos;
final Direction side = blockResult.getSide();
final BlockPos hitPos = blockResult.getBlockPos().offset(side);
if (!Platform.hasPermissions(new DimensionalCoord(w, hitPos), p)) {
return;
}
final BlockState whatsThere = w.getBlockState(hitPos);
if (whatsThere.getMaterial().isReplaceable() && w.isAir(hitPos)) {
AEApi.instance().definitions().blocks().paint().maybeBlock().ifPresent(paintBlock -> {
w.setBlockState(hitPos, paintBlock.getDefaultState(), 3);
});
}
final BlockEntity te = w.getBlockEntity(hitPos);
if (te instanceof PaintSplotchesBlockEntity) {
final Vec3d hp = pos.getPos().subtract(hitPos.getX(), hitPos.getY(), hitPos.getZ());
((PaintSplotchesBlockEntity) te).addBlot(type, side.getOpposite(), hp);
}
}
}
}
private void standardAmmo(float penetration, final World w, final PlayerEntity p, final Vec3d Vec3d,
final Vec3d Vec3d1, final Vec3d direction, final double d0, final double d1, final double d2) {
boolean hasDestroyed = true;
while (penetration > 0 && hasDestroyed) {
hasDestroyed = false;
final Box bb = new Box(Math.min(Vec3d.x, Vec3d1.x), Math.min(Vec3d.y, Vec3d1.y),
Math.min(Vec3d.z, Vec3d1.z), Math.max(Vec3d.x, Vec3d1.x), Math.max(Vec3d.y, Vec3d1.y),
Math.max(Vec3d.z, Vec3d1.z)).expand(16, 16, 16);
Entity entity = null;
Vec3d entityIntersection = null;
final List list = w.getEntities(p, bb);
double closest = 9999999.0D;
for (int l = 0; l < list.size(); ++l) {
final Entity entity1 = (Entity) list.get(l);
if (entity1.isAlive() && entity1 != p && !(entity1 instanceof ItemEntity)) {
if (entity1.isAlive()) {
// prevent killing / flying of mounts.
if (entity1.isConnectedThroughVehicle(p)) {
continue;
}
final float f1 = 0.3F;
final Box boundingBox = entity1.getBoundingBox().expand(f1, f1, f1);
final Vec3d intersection = boundingBox.rayTrace(Vec3d, Vec3d1).orElse(null);
if (intersection != null) {
final double nd = Vec3d.squaredDistanceTo(intersection);
if (nd < closest) {
entity = entity1;
entityIntersection = intersection;
closest = nd;
}
}
}
}
}
RayTraceContext rayTraceContext = new RayTraceContext(Vec3d, Vec3d1, RayTraceContext.ShapeType.COLLIDER,
RayTraceContext.FluidHandling.NONE, p);
final Vec3d vec = new Vec3d(d0, d1, d2);
HitResult pos = w.rayTrace(rayTraceContext);
if (entity != null && pos.getType() != HitResult.Type.MISS
&& pos.getPos().squaredDistanceTo(vec) > closest) {
pos = new EntityHitResult(entity, entityIntersection);
} else if (entity != null && pos.getType() == HitResult.Type.MISS) {
pos = new EntityHitResult(entity, entityIntersection);
}
try {
AppEng.instance().sendToAllNearExcept(null, d0, d1, d2, 128, w,
new MatterCannonPacket(d0, d1, d2, (float) direction.x, (float) direction.y,
(float) direction.z, (byte) (pos.getType() == HitResult.Type.MISS ? 32
: pos.getPos().squaredDistanceTo(vec) + 1)));
} catch (final Exception err) {
AELog.debug(err);
}
if (pos.getType() != HitResult.Type.MISS) {
final DamageSource dmgSrc = new EntityDamageSource("matter_cannon", p);
if (pos instanceof EntityHitResult) {
EntityHitResult entityResult = (EntityHitResult) pos;
Entity entityHit = entityResult.getEntity();
final int dmg = (int) Math.ceil(penetration / 20.0f);
if (entityHit instanceof LivingEntity) {
final LivingEntity el = (LivingEntity) entityHit;
penetration -= dmg;
el.takeKnockback(0, -direction.x, -direction.z);
el.damage(dmgSrc, dmg);
if (!el.isAlive()) {
hasDestroyed = true;
}
} else if (entityHit instanceof ItemEntity) {
hasDestroyed = true;
entityHit.remove();
} else if (entityHit.damage(dmgSrc, dmg)) {
hasDestroyed = true;
}
} else if (pos instanceof BlockHitResult) {
BlockHitResult blockResult = (BlockHitResult) pos;
if (!AEConfig.instance().isFeatureEnabled(AEFeature.MASS_CANNON_BLOCK_DAMAGE)) {
penetration = 0;
} else {
BlockPos blockPos = blockResult.getBlockPos();
final BlockState bs = w.getBlockState(blockPos);
final float hardness = bs.getHardness(w, blockPos) * 9.0f;
if (hardness >= 0.0) {
if (penetration > hardness
&& Platform.hasPermissions(new DimensionalCoord(w, blockPos), p)) {
hasDestroyed = true;
penetration -= hardness;
penetration *= 0.60;
w.breakBlock(blockPos, true);
}
}
}
}
}
}
}
@Override
public boolean isEditable(final ItemStack is) {
return true;
}
@Override
public FixedItemInv getUpgradesInventory(final ItemStack is) {
return new CellUpgrades(is, 4);
}
@Override
public FixedItemInv getConfigInventory(final ItemStack is) {
return new CellConfig(is);
}
@Override
public FuzzyMode getFuzzyMode(final ItemStack is) {
final String fz = is.getOrCreateTag().getString("FuzzyMode");
try {
return FuzzyMode.valueOf(fz);
} catch (final Throwable t) {
return FuzzyMode.IGNORE_ALL;
}
}
@Override
public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {
is.getOrCreateTag().putString("FuzzyMode", fzMode.name());
}
@Override
public int getBytes(final ItemStack cellItem) {
return 512;
}
@Override
public int getBytesPerType(final ItemStack cellItem) {
return 8;
}
@Override
public int getTotalTypes(final ItemStack cellItem) {
return 1;
}
@Override
public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) {
final float pen = AEApi.instance().registries().matterCannon()
.getPenetration(requestedAddition.createItemStack());
if (pen > 0) {
return false;
}
if (requestedAddition.getItem() instanceof PaintBallItem) {
return false;
}
return true;
}
@Override
public boolean storableInStorageCell() {
return true;
}
@Override
public boolean isStorageCell(final ItemStack i) {
return true;
}
@Override
public double getIdleDrain() {
return 0.5;
}
@Override
public IStorageChannel<IAEItemStack> getChannel() {
return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class);
}
}
@@ -0,0 +1,160 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools.powered;
import java.util.List;
import java.util.Set;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import appeng.api.AEApi;
import appeng.api.config.FuzzyMode;
import appeng.api.implementations.guiobjects.IGuiItem;
import appeng.api.implementations.guiobjects.IGuiItemObject;
import appeng.api.implementations.items.IStorageCell;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.cells.ICellInventoryHandler;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.container.ContainerLocator;
import appeng.container.ContainerOpener;
import appeng.container.implementations.MEPortableCellContainer;
import appeng.core.AEConfig;
import appeng.core.localization.GuiText;
import appeng.items.contents.CellConfig;
import appeng.items.contents.CellUpgrades;
import appeng.items.contents.PortableCellViewer;
import appeng.items.tools.powered.powersink.AEBasePoweredItem;
public class PortableCellItem extends AEBasePoweredItem implements IStorageCell<IAEItemStack>, IGuiItem {
public PortableCellItem(Item.Settings props) {
super(AEConfig.instance().getPortableCellBattery(), props);
}
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity player, final Hand hand) {
ContainerOpener.openContainer(MEPortableCellContainer.TYPE, player, ContainerLocator.forHand(player, hand));
return new TypedActionResult<>(ActionResult.SUCCESS, player.getStackInHand(hand));
}
@Override
@Environment(EnvType.CLIENT)
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
super.appendTooltip(stack, world, lines, advancedTooltips);
final ICellInventoryHandler<IAEItemStack> cdi = AEApi.instance().registries().cell().getCellInventory(stack,
null, AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
AEApi.instance().client().addCellInformation(cdi, lines);
}
@Override
public int getBytes(final ItemStack cellItem) {
return 512;
}
@Override
public int getBytesPerType(final ItemStack cellItem) {
return 8;
}
@Override
public int getTotalTypes(final ItemStack cellItem) {
return 27;
}
@Override
public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) {
return false;
}
@Override
public boolean storableInStorageCell() {
return false;
}
@Override
public boolean isStorageCell(final ItemStack i) {
return true;
}
@Override
public double getIdleDrain() {
return 0.5;
}
@Override
public IStorageChannel<IAEItemStack> getChannel() {
return AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class);
}
@Override
public boolean isEditable(final ItemStack is) {
return true;
}
@Override
public FixedItemInv getUpgradesInventory(final ItemStack is) {
return new CellUpgrades(is, 2);
}
@Override
public FixedItemInv getConfigInventory(final ItemStack is) {
return new CellConfig(is);
}
@Override
public FuzzyMode getFuzzyMode(final ItemStack is) {
final String fz = is.getOrCreateTag().getString("FuzzyMode");
try {
return FuzzyMode.valueOf(fz);
} catch (final Throwable t) {
return FuzzyMode.IGNORE_ALL;
}
}
@Override
public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {
is.getOrCreateTag().putString("FuzzyMode", fzMode.name());
}
@Override
public IGuiItemObject getGuiObject(final ItemStack is, int playerInventorySlot, final World w, final BlockPos pos) {
return new PortableCellViewer(is, playerInventorySlot);
}
// FIXME FABRIC Needs a custom mixin
// FIXME FABRIC @Override
// FIXME FABRIC public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
// FIXME FABRIC return slotChanged;
// FIXME FABRIC }
}
@@ -0,0 +1,128 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools.powered;
import java.util.List;
import appeng.api.config.*;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import appeng.api.AEApi;
import appeng.api.features.IWirelessTermHandler;
import appeng.api.util.IConfigManager;
import appeng.core.AEConfig;
import appeng.core.localization.GuiText;
import appeng.items.tools.powered.powersink.AEBasePoweredItem;
import appeng.util.ConfigManager;
public class WirelessTerminalItem extends AEBasePoweredItem implements IWirelessTermHandler {
public WirelessTerminalItem(Item.Settings props) {
super(AEConfig.instance().getWirelessTerminalBattery(), props);
}
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity player, final Hand hand) {
AEApi.instance().registries().wireless().openWirelessTerminalGui(player.getStackInHand(hand), w, player, hand);
return new TypedActionResult<>(ActionResult.SUCCESS, player.getStackInHand(hand));
}
@Override
@Environment(EnvType.CLIENT)
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
super.appendTooltip(stack, world, lines, advancedTooltips);
if (stack.hasTag()) {
final CompoundTag tag = stack.getOrCreateTag();
if (tag != null) {
final String encKey = tag.getString("encryptionKey");
if (encKey == null || encKey.isEmpty()) {
lines.add(GuiText.Unlinked.textComponent());
} else {
lines.add(GuiText.Linked.textComponent());
}
}
} else {
lines.add(new TranslatableText("AppEng.GuiITooltip.Unlinked"));
}
}
@Override
public boolean canHandle(final ItemStack is) {
return AEApi.instance().definitions().items().wirelessTerminal().isSameAs(is);
}
@Override
public boolean usePower(final PlayerEntity player, final double amount, final ItemStack is) {
return this.extractAEPower(is, amount, Actionable.MODULATE) >= amount - 0.5;
}
@Override
public boolean hasPower(final PlayerEntity player, final double amt, final ItemStack is) {
return this.getAECurrentPower(is) >= amt;
}
@Override
public IConfigManager getConfigManager(final ItemStack target) {
final ConfigManager out = new ConfigManager((manager, settingName, newValue) -> {
final CompoundTag data = target.getOrCreateTag();
manager.writeToNBT(data);
});
out.registerSetting(appeng.api.config.Settings.SORT_BY, SortOrder.NAME);
out.registerSetting(appeng.api.config.Settings.VIEW_MODE, ViewItems.ALL);
out.registerSetting(appeng.api.config.Settings.SORT_DIRECTION, SortDir.ASCENDING);
out.readFromNBT(target.getOrCreateTag().copy());
return out;
}
@Override
public String getEncryptionKey(final ItemStack item) {
final CompoundTag tag = item.getOrCreateTag();
return tag.getString("encryptionKey");
}
@Override
public void setEncryptionKey(final ItemStack item, final String encKey, final String name) {
final CompoundTag tag = item.getOrCreateTag();
tag.putString("encryptionKey", encKey);
tag.putString("name", name);
}
// FIXME FABRIC Needs custom mixin
// FIXME FABRIC @Override
// FIXME FABRIC public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
// FIXME FABRIC return slotChanged;
// FIXME FABRIC }
}
@@ -0,0 +1,162 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.tools.powered.powersink;
import java.text.MessageFormat;
import java.util.List;
import java.util.function.DoubleSupplier;
import net.fabricmc.api.Environment;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import net.fabricmc.api.EnvType;
import appeng.api.config.AccessRestriction;
import appeng.api.config.Actionable;
import appeng.api.config.PowerUnits;
import appeng.api.implementations.items.IAEItemPowerStorage;
import appeng.core.localization.GuiText;
import appeng.items.AEBaseItem;
public abstract class AEBasePoweredItem extends AEBaseItem implements IAEItemPowerStorage {
private static final String CURRENT_POWER_NBT_KEY = "internalCurrentPower";
private static final String MAX_POWER_NBT_KEY = "internalMaxPower";
private final DoubleSupplier powerCapacity;
public AEBasePoweredItem(final DoubleSupplier powerCapacity, Settings props) {
super(props);
// FIXME this.setFull3D();
this.powerCapacity = powerCapacity;
}
@Environment(EnvType.CLIENT)
@Override
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
final CompoundTag tag = stack.getTag();
double internalCurrentPower = 0;
final double internalMaxPower = this.getAEMaxPower(stack);
if (tag != null) {
internalCurrentPower = tag.getDouble(CURRENT_POWER_NBT_KEY);
}
final double percent = internalCurrentPower / internalMaxPower;
lines.add(GuiText.StoredEnergy.textComponent().copy()
.append(':' + MessageFormat.format(" {0,number,#} ", internalCurrentPower))
.append(new TranslatableText(PowerUnits.AE.unlocalizedName))
.append(" - " + MessageFormat.format(" {0,number,#.##%} ", percent)));
}
@Override
public boolean isDamageable() {
return true;
}
@Override
public void appendStacks(ItemGroup group, DefaultedList<ItemStack> items) {
super.appendStacks(group, items);
if (this.isIn(group)) {
final ItemStack charged = new ItemStack(this, 1);
final CompoundTag tag = charged.getOrCreateTag();
tag.putDouble(CURRENT_POWER_NBT_KEY, this.getAEMaxPower(charged));
tag.putDouble(MAX_POWER_NBT_KEY, this.getAEMaxPower(charged));
items.add(charged);
}
}
// FIXME FABRIC Currently no direct equivalent
// FIXME FABRIC @Override
// FIXME FABRIC public double getDurabilityForDisplay(final ItemStack is) {
// FIXME FABRIC return 1 - this.getAECurrentPower(is) / this.getAEMaxPower(is);
// FIXME FABRIC }
// FIXME FABRIC
// FIXME FABRIC @Override
// FIXME FABRIC public boolean isDamaged(final ItemStack stack) {
// FIXME FABRIC return true;
// FIXME FABRIC }
// FIXME FABRIC
// FIXME FABRIC @Override
// FIXME FABRIC public void setDamage(final ItemStack stack, final int damage) {
// FIXME FABRIC
// FIXME FABRIC }
@Override
public double injectAEPower(final ItemStack is, final double amount, Actionable mode) {
final double maxStorage = this.getAEMaxPower(is);
final double currentStorage = this.getAECurrentPower(is);
final double required = maxStorage - currentStorage;
final double overflow = amount - required;
if (mode == Actionable.MODULATE) {
final CompoundTag data = is.getOrCreateTag();
final double toAdd = Math.min(amount, required);
data.putDouble(CURRENT_POWER_NBT_KEY, currentStorage + toAdd);
}
return Math.max(0, overflow);
}
@Override
public double extractAEPower(final ItemStack is, final double amount, Actionable mode) {
final double currentStorage = this.getAECurrentPower(is);
final double fulfillable = Math.min(amount, currentStorage);
if (mode == Actionable.MODULATE) {
final CompoundTag data = is.getOrCreateTag();
data.putDouble(CURRENT_POWER_NBT_KEY, currentStorage - fulfillable);
}
return fulfillable;
}
@Override
public double getAEMaxPower(final ItemStack is) {
return this.powerCapacity.getAsDouble();
}
@Override
public double getAECurrentPower(final ItemStack is) {
final CompoundTag data = is.getOrCreateTag();
return data.getDouble(CURRENT_POWER_NBT_KEY);
}
@Override
public AccessRestriction getPowerFlow(final ItemStack is) {
return AccessRestriction.WRITE;
}
// FIXME FABRIC @Override
// FIXME FABRIC public ICapabilityProvider initCapabilities(ItemStack stack, CompoundTag nbt) {
// FIXME FABRIC return new PoweredItemCapabilities(stack, this);
// FIXME FABRIC }
}