Moving to source sets

This commit is contained in:
Sebastian Hartte
2020-07-01 23:36:51 +02:00
parent f2e3d81fd7
commit 2642ced86b
2924 changed files with 794 additions and 796 deletions
@@ -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;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public abstract class AEBaseItem extends Item {
public AEBaseItem(Item.Settings properties) {
super(properties);
}
@Override
public String toString() {
Identifier id = Registry.ITEM.getId(this);
String regName = id != Registry.ITEM.getDefaultId() ? id.getPath() : "unregistered";
return this.getClass().getSimpleName() + "[" + regName + "]";
}
@Override
public boolean canRepair(ItemStack stack, ItemStack ingredient) {
return false;
}
}
@@ -0,0 +1,40 @@
/*
* 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.contents;
import alexiil.mc.lib.attributes.item.FixedItemInvView;
import net.minecraft.item.ItemStack;
import appeng.tile.inventory.AppEngInternalInventory;
public class CellConfig extends AppEngInternalInventory {
private final ItemStack is;
public CellConfig(final ItemStack is) {
super(null, 63);
this.is = is;
this.readFromNBT(is.getOrCreateTag(), "list");
}
@Override
protected void onContentsChanged(FixedItemInvView inv, int slot, ItemStack previous, ItemStack current) {
this.writeToNBT(this.is.getOrCreateTag(), "list");
}
}
@@ -0,0 +1,39 @@
/*
* 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.contents;
import alexiil.mc.lib.attributes.item.FixedItemInvView;
import net.minecraft.item.ItemStack;
import appeng.parts.automation.StackUpgradeInventory;
public final class CellUpgrades extends StackUpgradeInventory {
private final ItemStack is;
public CellUpgrades(final ItemStack is, final int upgrades) {
super(is, null, upgrades);
this.is = is;
this.readFromNBT(is.getOrCreateTag(), "upgrades");
}
@Override
protected void onContentsChanged(FixedItemInvView inv, int slot, ItemStack previous, ItemStack current) {
this.writeToNBT(this.is.getOrCreateTag(), "upgrades");
}
}
@@ -0,0 +1,90 @@
/*
* 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.contents;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import net.minecraft.item.ItemStack;
import appeng.api.implementations.guiobjects.INetworkTool;
import appeng.api.implementations.items.IUpgradeModule;
import appeng.api.networking.IGridHost;
import appeng.tile.inventory.AppEngInternalInventory;
import appeng.util.inv.IAEAppEngInventory;
import appeng.util.inv.InvOperation;
import appeng.util.inv.filter.IAEItemFilter;
public class NetworkToolViewer implements INetworkTool, IAEAppEngInventory {
private final AppEngInternalInventory inv;
private final ItemStack is;
private final IGridHost gh;
public NetworkToolViewer(final ItemStack is, final IGridHost gHost) {
this.is = is;
this.gh = gHost;
this.inv = new AppEngInternalInventory(this, 9);
this.inv.setFilter(new NetworkToolInventoryFilter());
if (is.hasTag()) // prevent crash when opening network status screen.
{
this.inv.readFromNBT(is.getOrCreateTag(), "inv");
}
}
@Override
public void saveChanges() {
this.inv.writeToNBT(this.is.getOrCreateTag(), "inv");
}
@Override
public void onChangeInventory(FixedItemInv inv, int slot, InvOperation mc, ItemStack removedStack,
ItemStack newStack) {
}
@Override
public ItemStack getItemStack() {
return this.is;
}
@Override
public IGridHost getGridHost() {
return this.gh;
}
private static class NetworkToolInventoryFilter implements IAEItemFilter {
@Override
public boolean allowExtract(FixedItemInv inv, int slot, int amount) {
return true;
}
@Override
public boolean allowInsert(FixedItemInv inv, int slot, ItemStack stack) {
return stack.getItem() instanceof IUpgradeModule
&& ((IUpgradeModule) stack.getItem()).getType(stack) != null;
}
}
public FixedItemInv getInternalInventory() {
return this.inv;
}
@Override
public FixedItemInv getInventory() {
return this.inv;
}
}
@@ -0,0 +1,100 @@
/*
* 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.contents;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.PowerMultiplier;
import appeng.api.config.Settings;
import appeng.api.config.SortDir;
import appeng.api.config.SortOrder;
import appeng.api.config.ViewItems;
import appeng.api.implementations.guiobjects.IPortableCell;
import appeng.api.implementations.items.IAEItemPowerStorage;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.util.IConfigManager;
import appeng.container.interfaces.IInventorySlotAware;
import appeng.me.helpers.MEMonitorHandler;
import appeng.util.ConfigManager;
public class PortableCellViewer extends MEMonitorHandler<IAEItemStack> implements IPortableCell, IInventorySlotAware {
private final ItemStack target;
private final IAEItemPowerStorage ips;
private final int inventorySlot;
public PortableCellViewer(final ItemStack is, final int slot) {
super(AEApi.instance().registries().cell().getCellInventory(is, null,
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)));
this.ips = (IAEItemPowerStorage) is.getItem();
this.target = is;
this.inventorySlot = slot;
}
@Override
public int getInventorySlot() {
return this.inventorySlot;
}
@Override
public ItemStack getItemStack() {
return this.target;
}
@Override
public double extractAEPower(double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier) {
amt = usePowerMultiplier.multiply(amt);
if (mode == Actionable.SIMULATE) {
return usePowerMultiplier.divide(Math.min(amt, this.ips.getAECurrentPower(this.target)));
}
return usePowerMultiplier.divide(this.ips.extractAEPower(this.target, amt, Actionable.MODULATE));
}
@Override
public <T extends IAEStack<T>> IMEMonitor<T> getInventory(IStorageChannel<T> channel) {
if (channel == AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class)) {
return (IMEMonitor<T>) this;
}
return null;
}
@Override
public IConfigManager getConfigManager() {
final ConfigManager out = new ConfigManager((manager, settingName, newValue) -> {
final CompoundTag data = this.target.getOrCreateTag();
manager.writeToNBT(data);
});
out.registerSetting(Settings.SORT_BY, SortOrder.NAME);
out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL);
out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING);
out.readFromNBT(this.target.getOrCreateTag().copy());
return out;
}
}
@@ -0,0 +1,37 @@
/*
* 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.contents;
import net.minecraft.item.ItemStack;
import appeng.api.implementations.guiobjects.IGuiItemObject;
public class QuartzKnifeObj implements IGuiItemObject {
private final ItemStack is;
public QuartzKnifeObj(final ItemStack o) {
this.is = o;
}
@Override
public ItemStack getItemStack() {
return this.is;
}
}
@@ -0,0 +1,204 @@
/*
* 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.materials;
import java.util.List;
import appeng.hooks.AEToolItem;
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.block.entity.BlockEntity;
import net.minecraft.text.LiteralText;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.TypedActionResult;
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.config.Upgrades;
import appeng.api.implementations.IUpgradeableHost;
import appeng.api.implementations.items.IStorageComponent;
import appeng.api.implementations.items.IUpgradeModule;
import appeng.api.implementations.tiles.ISegmentedInventory;
import appeng.api.parts.IPartHost;
import appeng.api.parts.SelectedPart;
import appeng.items.AEBaseItem;
import appeng.util.InventoryAdaptor;
import appeng.util.inv.AdaptorFixedInv;
public final class MaterialItem extends AEBaseItem implements IStorageComponent, IUpgradeModule, AEToolItem {
/**
* NBT property used by the name press to store the name to be inscribed.
*/
public static final String TAG_INSCRIBE_NAME = "InscribeName";
private static final int KILO_SCALAR = 1024;
private final MaterialType materialType;
public MaterialItem(Settings properties, MaterialType materialType) {
super(properties);
this.materialType = materialType;
}
@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);
if (materialType == MaterialType.NAME_PRESS) {
final CompoundTag c = stack.getOrCreateTag();
if (c.contains(TAG_INSCRIBE_NAME)) {
lines.add(new LiteralText(c.getString(TAG_INSCRIBE_NAME)));
}
}
final Upgrades u = this.getType(stack);
if (u != null) {
lines.addAll(u.getTooltipLines());
}
}
@Override
public Upgrades getType(final ItemStack itemstack) {
switch (materialType) {
case CARD_CAPACITY:
return Upgrades.CAPACITY;
case CARD_FUZZY:
return Upgrades.FUZZY;
case CARD_REDSTONE:
return Upgrades.REDSTONE;
case CARD_SPEED:
return Upgrades.SPEED;
case CARD_INVERTER:
return Upgrades.INVERTER;
case CARD_CRAFTING:
return Upgrades.CRAFTING;
default:
return null;
}
}
@Override
public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
return super.use(world, user, hand);
}
@Override
public ActionResult onItemUseFirst(ItemStack stack, ItemUsageContext context) {
PlayerEntity player = context.getPlayer();
Hand hand = context.getHand();
if (player.isInSneakingPose()) {
final BlockEntity te = context.getWorld().getBlockEntity(context.getBlockPos());
FixedItemInv upgrades = null;
if (te instanceof IPartHost) {
final SelectedPart sp = ((IPartHost) te).selectPart(context.getHitPos());
if (sp.part instanceof IUpgradeableHost) {
upgrades = ((ISegmentedInventory) sp.part).getInventoryByName("upgrades");
}
} else if (te instanceof IUpgradeableHost) {
upgrades = ((ISegmentedInventory) te).getInventoryByName("upgrades");
}
if (upgrades != null && !player.getStackInHand(hand).isEmpty()
&& player.getStackInHand(hand).getItem() instanceof IUpgradeModule) {
final IUpgradeModule um = (IUpgradeModule) player.getStackInHand(hand).getItem();
final Upgrades u = um.getType(player.getStackInHand(hand));
if (u != null) {
if (player.world.isClient) {
return ActionResult.PASS;
}
final InventoryAdaptor ad = new AdaptorFixedInv(upgrades);
player.setStackInHand(hand, ad.addItems(player.getStackInHand(hand)));
return ActionResult.SUCCESS;
}
}
}
return ActionResult.PASS;
}
// FIXME FABRIC @Override
// FIXME FABRIC public boolean hasCustomEntity(final ItemStack is) {
// FIXME FABRIC return materialType.hasCustomEntity();
// FIXME FABRIC }
// FIXME FABRIC @Override
// FIXME FABRIC public Entity createEntity(final World w, final Entity location, final ItemStack itemstack) {
// FIXME FABRIC final Class<? extends Entity> droppedEntity = materialType.getCustomEntityClass();
// FIXME FABRIC final Entity eqi;
// FIXME FABRIC try {
// FIXME FABRIC eqi = droppedEntity.getConstructor(World.class, double.class, double.class, double.class, ItemStack.class)
// FIXME FABRIC .newInstance(w, location.getX(), location.getY(), location.getZ(), itemstack);
// FIXME FABRIC } catch (final Throwable t) {
// FIXME FABRIC throw new IllegalStateException(t);
// FIXME FABRIC }
// FIXME FABRIC eqi.setVelocity(location.getVelocity());
// FIXME FABRIC if (location instanceof ItemEntity && eqi instanceof ItemEntity) {
// FIXME FABRIC ((ItemEntity) eqi).setDefaultPickupDelay();
// FIXME FABRIC }
// FIXME FABRIC return eqi;
// FIXME FABRIC }
@Override
public int getBytes(final ItemStack is) {
switch (materialType) {
case ITEM_1K_CELL_COMPONENT:
return KILO_SCALAR;
case ITEM_4K_CELL_COMPONENT:
return KILO_SCALAR * 4;
case ITEM_16K_CELL_COMPONENT:
return KILO_SCALAR * 16;
case ITEM_64K_CELL_COMPONENT:
return KILO_SCALAR * 64;
default:
}
return 0;
}
@Override
public boolean isStorageComponent(final ItemStack is) {
switch (materialType) {
case ITEM_1K_CELL_COMPONENT:
case ITEM_4K_CELL_COMPONENT:
case ITEM_16K_CELL_COMPONENT:
case ITEM_64K_CELL_COMPONENT:
return true;
default:
}
return false;
}
}
@@ -0,0 +1,194 @@
/*
* 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.materials;
import java.util.EnumSet;
import java.util.Set;
import net.minecraft.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Identifier;
import appeng.api.features.AEFeature;
import appeng.core.AppEng;
import appeng.entity.ChargedQuartzEntity;
import appeng.entity.SingularityEntity;
public enum MaterialType {
CERTUS_QUARTZ_CRYSTAL("certus_quartz_crystal", EnumSet.of(AEFeature.CERTUS), "crystalCertusQuartz"),
CERTUS_QUARTZ_CRYSTAL_CHARGED("charged_certus_quartz_crystal", EnumSet.of(AEFeature.CERTUS),
ChargedQuartzEntity.class),
CERTUS_QUARTZ_DUST("certus_quartz_dust", EnumSet.of(AEFeature.DUSTS, AEFeature.CERTUS), "dustCertusQuartz"),
NETHER_QUARTZ_DUST("nether_quartz_dust", EnumSet.of(AEFeature.DUSTS), "dustNetherQuartz,dustQuartz"),
FLOUR("flour", EnumSet.of(AEFeature.FLOUR), "dustWheat"),
GOLD_DUST("gold_dust", EnumSet.of(AEFeature.DUSTS), "dustGold"),
IRON_DUST("iron_dust", EnumSet.of(AEFeature.DUSTS), "dustIron"),
SILICON("silicon", EnumSet.of(AEFeature.SILICON), "itemSilicon"),
MATTER_BALL("matter_ball", EnumSet.of(AEFeature.MATTER_BALL)),
FLUIX_CRYSTAL("fluix_crystal", EnumSet.of(AEFeature.FLUIX), "crystalFluix"),
FLUIX_DUST("fluix_dust", EnumSet.of(AEFeature.FLUIX, AEFeature.DUSTS), "dustFluix"),
FLUIX_PEARL("fluix_pearl", EnumSet.of(AEFeature.FLUIX), "pearlFluix"),
PURIFIED_CERTUS_QUARTZ_CRYSTAL("purified_certus_quartz_crystal",
EnumSet.of(AEFeature.CERTUS, AEFeature.PURE_CRYSTALS), "crystalPureCertusQuartz"),
PURIFIED_NETHER_QUARTZ_CRYSTAL("purified_nether_quartz_crystal", EnumSet.of(AEFeature.PURE_CRYSTALS),
"crystalPureNetherQuartz"),
PURIFIED_FLUIX_CRYSTAL("purified_fluix_crystal", EnumSet.of(AEFeature.FLUIX, AEFeature.PURE_CRYSTALS),
"crystalPureFluix"),
CALCULATION_PROCESSOR_PRESS("calculation_processor_press", EnumSet.of(AEFeature.PRESSES)),
ENGINEERING_PROCESSOR_PRESS("engineering_processor_press", EnumSet.of(AEFeature.PRESSES)),
LOGIC_PROCESSOR_PRESS("logic_processor_press", EnumSet.of(AEFeature.PRESSES)),
CALCULATION_PROCESSOR_PRINT("printed_calculation_processor", EnumSet.of(AEFeature.PRINTED_CIRCUITS)),
ENGINEERING_PROCESSOR_PRINT("printed_engineering_processor", EnumSet.of(AEFeature.PRINTED_CIRCUITS)),
LOGIC_PROCESSOR_PRINT("printed_logic_processor", EnumSet.of(AEFeature.PRINTED_CIRCUITS)),
SILICON_PRESS("silicon_press", EnumSet.of(AEFeature.PRESSES)),
SILICON_PRINT("printed_silicon", EnumSet.of(AEFeature.PRINTED_CIRCUITS)),
NAME_PRESS("name_press", EnumSet.of(AEFeature.PRESSES)),
LOGIC_PROCESSOR("logic_processor", EnumSet.of(AEFeature.PROCESSORS)),
CALCULATION_PROCESSOR("calculation_processor", EnumSet.of(AEFeature.PROCESSORS)),
ENGINEERING_PROCESSOR("engineering_processor", EnumSet.of(AEFeature.PROCESSORS)),
// Basic Cards
BASIC_CARD("basic_card", EnumSet.of(AEFeature.BASIC_CARDS)),
CARD_REDSTONE("redstone_card", EnumSet.of(AEFeature.BASIC_CARDS)),
CARD_CAPACITY("capacity_card", EnumSet.of(AEFeature.BASIC_CARDS)),
// Adv Cards
ADVANCED_CARD("advanced_card", EnumSet.of(AEFeature.ADVANCED_CARDS)),
CARD_FUZZY("fuzzy_card", EnumSet.of(AEFeature.ADVANCED_CARDS)),
CARD_SPEED("speed_card", EnumSet.of(AEFeature.ADVANCED_CARDS)),
CARD_INVERTER("inverter_card", EnumSet.of(AEFeature.ADVANCED_CARDS)),
SPATIAL_2_CELL_COMPONENT("2_cubed_spatial_cell_component", EnumSet.of(AEFeature.SPATIAL_IO)),
SPATIAL_16_CELL_COMPONENT("16_cubed_spatial_cell_component", EnumSet.of(AEFeature.SPATIAL_IO)),
SPATIAL_128_CELL_COMPONENT("128_cubed_spatial_cell_component", EnumSet.of(AEFeature.SPATIAL_IO)),
ITEM_1K_CELL_COMPONENT("1k_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS)),
ITEM_4K_CELL_COMPONENT("4k_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS)),
ITEM_16K_CELL_COMPONENT("16k_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS)),
ITEM_64K_CELL_COMPONENT("64k_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS)),
EMPTY_STORAGE_CELL("empty_storage_cell", EnumSet.of(AEFeature.STORAGE_CELLS)),
WOODEN_GEAR("wooden_gear", EnumSet.of(AEFeature.GRIND_STONE), "gearWood"),
WIRELESS_RECEIVER("wireless_receiver", EnumSet.of(AEFeature.WIRELESS_ACCESS_TERMINAL)),
WIRELESS_BOOSTER("wireless_booster", EnumSet.of(AEFeature.WIRELESS_ACCESS_TERMINAL)),
FORMATION_CORE("formation_core", EnumSet.of(AEFeature.CORES)),
ANNIHILATION_CORE("annihilation_core", EnumSet.of(AEFeature.CORES)),
SKY_DUST("sky_dust", EnumSet.of(AEFeature.DUSTS)),
ENDER_DUST("ender_dust", EnumSet.of(AEFeature.QUANTUM_NETWORK_BRIDGE), "dustEnder,dustEnderPearl",
SingularityEntity.class),
SINGULARITY("singularity", EnumSet.of(AEFeature.QUANTUM_NETWORK_BRIDGE), SingularityEntity.class),
QUANTUM_ENTANGLED_SINGULARITY("quantum_entangled_singularity", EnumSet.of(AEFeature.QUANTUM_NETWORK_BRIDGE),
SingularityEntity.class),
BLANK_PATTERN("blank_pattern", EnumSet.of(AEFeature.PATTERNS)),
CARD_CRAFTING("crafting_card", EnumSet.of(AEFeature.ADVANCED_CARDS, AEFeature.CRAFTING_CPU)),
FLUID_1K_CELL_COMPONENT("1k_fluid_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS)),
FLUID_4K_CELL_COMPONENT("4k_fluid_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS)),
FLUID_16K_CELL_COMPONENT("16k_fluid_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS)),
FLUID_64K_CELL_COMPONENT("64k_fluid_cell_component", EnumSet.of(AEFeature.STORAGE_CELLS));
private final Set<AEFeature> features;
private final Identifier registryName;
private Item itemInstance;
private String oreName;
private Class<? extends Entity> droppedEntity;
private boolean isRegistered = false;
MaterialType(String id, final Set<AEFeature> features) {
this.features = features;
this.registryName = new Identifier(AppEng.MOD_ID, id);
}
MaterialType(String id, final Set<AEFeature> features, final Class<? extends Entity> c) {
this(id, features);
this.droppedEntity = c;
}
MaterialType(String id, final Set<AEFeature> features, final String oreDictionary,
final Class<? extends Entity> c) {
this(id, features);
this.oreName = oreDictionary;
this.droppedEntity = c;
}
MaterialType(String id, final Set<AEFeature> features, final String oreDictionary) {
this(id, features);
this.oreName = oreDictionary;
}
public ItemStack stack(final int size) {
return new ItemStack(this.getItemInstance(), size);
}
public Set<AEFeature> getFeature() {
return this.features;
}
public String getOreName() {
return this.oreName;
}
boolean hasCustomEntity() {
return this.droppedEntity != null;
}
Class<? extends Entity> getCustomEntityClass() {
return this.droppedEntity;
}
public boolean isRegistered() {
return this.isRegistered;
}
public void markReady() {
this.isRegistered = true;
}
public Item getItemInstance() {
return this.itemInstance;
}
public void setItemInstance(final Item itemInstance) {
this.itemInstance = itemInstance;
}
public String getId() {
return registryName.getPath();
}
public Identifier getRegistryName() {
return this.registryName;
}
}
@@ -1,156 +0,0 @@
/*
* 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.getTranslationKey());
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) + "%");
}
@Override
public boolean hasCustomEntity(final ItemStack stack) {
return true;
}
@Override
public Entity createEntity(final World world, final Entity location, final ItemStack itemstack) {
final GrowingCrystalEntity egc = new GrowingCrystalEntity(world, location.getX(), location.getY(),
location.getZ(), itemstack);
egc.setVelocity(location.getVelocity());
// Cannot read the pickup delay of the original item, so we
// use the pickup delay used for items dropped by a player instead
egc.setPickupDelay(40);
return egc;
}
@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);
}
}
}
@@ -1,207 +0,0 @@
/*
* 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 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.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 {
// 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.setDisplayName(GuiText.InvalidPattern.textComponent().formatted(Formatting.RED));
InvalidPatternHelper invalid = new InvalidPatternHelper(stack);
final Text label = (invalid.isCraftable() ? GuiText.Crafts.textComponent()
: GuiText.Creates.textComponent()).append(": ");
final Text and = new LiteralText(" ").append(GuiText.And.textComponent())
.append(" ");
final Text with = GuiText.With.textComponent().append(": ");
boolean first = true;
for (final InvalidPatternHelper.PatternIngredient output : invalid.getOutputs()) {
lines.add((first ? label : and).deepCopy().append(output.getFormattedToolTip()));
first = false;
}
first = true;
for (final InvalidPatternHelper.PatternIngredient input : invalid.getInputs()) {
lines.add((first ? with : and).deepCopy().append(input.getFormattedToolTip()));
first = false;
}
if (invalid.isCraftable()) {
final Text substitutionLabel = GuiText.Substitute.textComponent().append(" ");
final Text canSubstitute = invalid.canSubstitute() ? GuiText.Yes.textComponent()
: GuiText.No.textComponent();
lines.add(substitutionLabel.append(canSubstitute));
}
return;
}
if (stack.hasCustomName()) {
stack.removeChildTag("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())
.append(": ");
final Text and = new LiteralText(" ").append(GuiText.And.textComponent())
.append(" ");
final Text with = GuiText.With.textComponent().append(": ");
boolean first = true;
for (final IAEItemStack anOut : out) {
if (anOut == null) {
continue;
}
lines.add((first ? label : and).deepCopy().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).deepCopy().append(anIn.getStackSize() + "x ")
.append(Platform.getItemDisplayName(anIn)));
first = false;
}
if (isCrafting) {
final Text substitutionLabel = GuiText.Substitute.textComponent().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;
}
}
@@ -1,56 +0,0 @@
/*
* 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,23 @@
package appeng.items.parts;
import java.util.function.Function;
import net.minecraft.item.ItemStack;
import appeng.api.parts.IPart;
import appeng.api.util.AEColor;
public class ColoredPartItem<T extends IPart> extends PartItem<T> {
private final AEColor color;
public ColoredPartItem(Settings properties, Function<ItemStack, T> factory, AEColor color) {
super(properties, factory);
this.color = color;
}
public AEColor getColor() {
return color;
}
}
@@ -0,0 +1,208 @@
/*
* 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.parts;
import appeng.hooks.AEToolItem;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.api.EnvironmentInterface;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRenderType;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.RenderLayers;
import net.minecraft.item.*;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.tag.BlockTags;
import net.minecraft.tag.Tag;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Identifier;
import net.minecraft.util.collection.DefaultedList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.text.Text;
import net.minecraft.world.EmptyBlockView;
import appeng.api.AEApi;
import appeng.api.exceptions.MissingDefinitionException;
import appeng.api.features.AEFeature;
import appeng.api.parts.IAlphaPassItem;
import appeng.api.util.AEPartLocation;
import appeng.core.AEConfig;
import appeng.core.AppEng;
import appeng.facade.FacadePart;
import appeng.facade.IFacadeItem;
import appeng.items.AEBaseItem;
@EnvironmentInterface(value = EnvType.CLIENT, itf=IAlphaPassItem.class)
public class FacadeItem extends AEBaseItem implements IFacadeItem, IAlphaPassItem, AEToolItem {
/**
* Block tag used to explicitly whitelist blocks for use in facades.
*/
private static final Identifier TAG_WHITELISTED = new Identifier(AppEng.MOD_ID, "whitelisted/facades");
private static final String NBT_ITEM_ID = "item";
public FacadeItem(Settings properties) {
super(properties);
}
@Override
public ActionResult onItemUseFirst(ItemStack stack, ItemUsageContext context) {
return AEApi.instance().partHelper().placeBus(stack, context.getBlockPos(), context.getSide(), context.getPlayer(),
context.getHand(), context.getWorld());
}
@Override
public Text getName(ItemStack is) {
try {
final ItemStack in = this.getTextureItem(is);
if (!in.isEmpty()) {
return super.getName(is).copy().append(" - ").append(in.getName());
}
} catch (final Throwable ignored) {
}
return super.getName(is);
}
@Override
public void appendStacks(ItemGroup group, DefaultedList<ItemStack> items) {
}
public ItemStack createFacadeForItem(final ItemStack itemStack, final boolean returnItem) {
if (itemStack.isEmpty() || itemStack.hasTag() || !(itemStack.getItem() instanceof BlockItem)) {
return ItemStack.EMPTY;
}
BlockItem blockItem = (BlockItem) itemStack.getItem();
Block block = blockItem.getBlock();
if (block == Blocks.AIR) {
return ItemStack.EMPTY;
}
// We only support the default state for facades. Sorry.
BlockState blockState = block.getDefaultState();
final boolean areTileEntitiesEnabled = AEConfig.instance().isFeatureEnabled(AEFeature.TILE_ENTITY_FACADES);
Tag<Block> whitelistTag = BlockTags.getContainer().getOrCreate(TAG_WHITELISTED);
final boolean isWhiteListed = block.isIn(whitelistTag);
final boolean isModel = blockState.getRenderType() == BlockRenderType.MODEL;
final BlockState defaultState = block.getDefaultState();
final boolean isTileEntity = block.hasBlockEntity();
final boolean isFullCube = defaultState.isOpaqueFullCube(EmptyBlockView.INSTANCE, BlockPos.ORIGIN);
final boolean isTileEntityAllowed = !isTileEntity || (areTileEntitiesEnabled && isWhiteListed);
final boolean isBlockAllowed = isFullCube || isWhiteListed;
if (isModel && isTileEntityAllowed && isBlockAllowed) {
if (returnItem) {
return itemStack;
}
final ItemStack is = new ItemStack(this);
final CompoundTag data = new CompoundTag();
Identifier itemId = Registry.ITEM.getId(itemStack.getItem());
data.putString(NBT_ITEM_ID, itemId.toString());
is.setTag(data);
return is;
}
return ItemStack.EMPTY;
}
@Override
public FacadePart createPartFromItemStack(final ItemStack is, final AEPartLocation side) {
final ItemStack in = this.getTextureItem(is);
if (!in.isEmpty()) {
return new FacadePart(is, side);
}
return null;
}
@Override
public ItemStack getTextureItem(ItemStack is) {
CompoundTag nbt = is.getTag();
if (nbt == null) {
return ItemStack.EMPTY;
}
Identifier itemId = new Identifier(nbt.getString(NBT_ITEM_ID));
Item baseItem = Registry.ITEM.getOrEmpty(itemId).orElse(null);
if (baseItem == null) {
return ItemStack.EMPTY;
}
return new ItemStack(baseItem);
}
@Override
public BlockState getTextureBlockState(ItemStack is) {
ItemStack baseItemStack = this.getTextureItem(is);
if (baseItemStack.isEmpty()) {
return Blocks.GLASS.getDefaultState();
}
Block block = Block.getBlockFromItem(baseItemStack.getItem());
if (block == Blocks.AIR) {
return Blocks.GLASS.getDefaultState();
}
return block.getDefaultState();
}
public ItemStack createFromID(final int id) {
ItemStack facadeStack = AEApi.instance().definitions().items().facade().maybeStack(1).orElseThrow(
() -> new MissingDefinitionException("Tried to create a facade, while facades are being deactivated."));
// Convert back to a registry name...
Item item = Registry.ITEM.get(id);
if (item == Items.AIR) {
return ItemStack.EMPTY;
}
Identifier longId = Registry.ITEM.getId(item);
final CompoundTag facadeTag = new CompoundTag();
facadeTag.putString(NBT_ITEM_ID, longId.toString());
facadeStack.setTag(facadeTag);
return facadeStack;
}
@Environment(EnvType.CLIENT)
@Override
public boolean useAlphaPass(final ItemStack is) {
BlockState blockState = this.getTextureBlockState(is);
if (blockState == null) {
return false;
}
return RenderLayers.getBlockLayer(blockState) == RenderLayer.getTranslucent()
|| RenderLayers.getBlockLayer(blockState) == RenderLayer.getTranslucentNoCrumbling();
}
}
@@ -0,0 +1,59 @@
/*
* 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.parts;
import java.util.function.Function;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.util.ActionResult;
import appeng.api.AEApi;
import appeng.api.parts.IPart;
import appeng.api.parts.IPartItem;
import appeng.items.AEBaseItem;
public class PartItem<T extends IPart> extends AEBaseItem implements IPartItem<T> {
private final Function<ItemStack, T> factory;
public PartItem(Settings properties, Function<ItemStack, T> factory) {
super(properties);
this.factory = factory;
}
@Override
public ActionResult useOnBlock(ItemUsageContext context) {
PlayerEntity player = context.getPlayer();
ItemStack held = player.getStackInHand(context.getHand());
if (held.getItem() != this) {
return ActionResult.PASS;
}
return AEApi.instance().partHelper().placeBus(held, context.getBlockPos(), context.getSide(), player,
context.getHand(), context.getWorld());
}
@Override
public T createPart(ItemStack is) {
return factory.apply(is);
}
}
@@ -16,29 +16,31 @@
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.items.misc;
package appeng.items.parts;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import appeng.api.util.AEColor;
import appeng.items.AEBaseItem;
import appeng.bootstrap.IItemRendering;
import appeng.bootstrap.ItemRenderingCustomizer;
import appeng.client.render.StaticItemColor;
public class PaintBallItem extends AEBaseItem {
public class PartItemRendering extends ItemRenderingCustomizer {
private final AEColor color;
private final boolean lumen;
public PartItemRendering() {
this.color = AEColor.TRANSPARENT;
}
public PaintBallItem(Settings properties, AEColor color, boolean lumen) {
super(properties);
public PartItemRendering(AEColor color) {
this.color = color;
this.lumen = lumen;
}
public AEColor getColor() {
return color;
@Override
@Environment(EnvType.CLIENT)
public void customize(IItemRendering rendering) {
rendering.color(new StaticItemColor(color));
}
public boolean isLumen() {
return lumen;
}
}
@@ -0,0 +1,34 @@
/*
* 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.parts;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation is used to mark static fields or static methods that
* return/contain models used for a part. They are automatically registered as
* part of the part item registration.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD })
public @interface PartModels {
}
@@ -0,0 +1,124 @@
package appeng.items.parts;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.minecraft.util.Identifier;
import appeng.api.parts.IPartModel;
import appeng.core.AELog;
/**
* Helps with the reflection magic needed to gather all models for AE2 cable bus
* parts.
*/
public class PartModelsHelper {
public static List<Identifier> createModels(Class<?> clazz) {
List<Identifier> locations = new ArrayList<>();
// Check all static fields for used models
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.getAnnotation(PartModels.class) == null) {
continue;
}
if (!Modifier.isStatic(field.getModifiers())) {
AELog.error("The @PartModels annotation can only be used on static fields or methods. Was seen on: "
+ field);
continue;
}
Object value;
try {
field.setAccessible(true);
value = field.get(null);
} catch (IllegalAccessException e) {
AELog.error(e, "Cannot access field annotated with @PartModels: " + field);
continue;
}
convertAndAddLocation(field, value, locations);
}
// Check all static methods for the annotation
for (Method method : clazz.getDeclaredMethods()) {
if (method.getAnnotation(PartModels.class) == null) {
continue;
}
if (!Modifier.isStatic(method.getModifiers())) {
AELog.error("The @PartModels annotation can only be used on static fields or methods. Was seen on: "
+ method);
continue;
}
// Check for parameter count
if (method.getParameters().length != 0) {
AELog.error(
"The @PartModels annotation can only be used on static methods without parameters. Was seen on: "
+ method);
continue;
}
// Make sure we can handle the return type
Class<?> returnType = method.getReturnType();
if (!Identifier.class.isAssignableFrom(returnType)
&& !Collection.class.isAssignableFrom(returnType)) {
AELog.error(
"The @PartModels annotation can only be used on static methods that return a ResourceLocation or Collection of "
+ "ResourceLocations. Was seen on: " + method);
continue;
}
Object value;
try {
method.setAccessible(true);
value = method.invoke(null);
} catch (IllegalAccessException | InvocationTargetException e) {
AELog.error(e, "Failed to invoke the @PartModels annotated method " + method);
continue;
}
convertAndAddLocation(method, value, locations);
}
if (clazz.getSuperclass() != null) {
locations.addAll(createModels(clazz.getSuperclass()));
}
return locations;
}
private static void convertAndAddLocation(Object source, Object value, List<Identifier> locations) {
if (value == null) {
return;
}
if (value instanceof Identifier) {
locations.add((Identifier) value);
} else if (value instanceof IPartModel) {
locations.addAll(((IPartModel) value).getModels());
} else if (value instanceof Collection) {
// Check that each object is an IPartModel
Collection<?> values = (Collection<?>) value;
for (Object candidate : values) {
if (!(candidate instanceof IPartModel)) {
AELog.error("List of locations obtained from {} contains a non resource location: {}", source,
candidate);
continue;
}
locations.addAll(((IPartModel) candidate).getModels());
}
}
}
}
@@ -1,206 +0,0 @@
/*
* 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 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> {
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.getCurrentItem() == stack) {
final InventoryAdaptor ia = InventoryAdaptor.getAdaptor(player);
final IItemList<IAEItemStack> list = inv.getAvailableItems(this.getChannel().createList());
if (list.isEmpty() && ia != null) {
playerInventory.setStack(playerInventory.currentItem, 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.container != null) {
player.container.detectAndSendChanges();
}
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;
}
@Override
public ItemStack getRecipeRemainder(final ItemStack itemStack) {
return AEApi.instance().definitions().materials().emptyStorageCell().maybeStack(1)
.orElseThrow(() -> new MissingDefinitionException(
"Tried to use empty storage cells while basic storage cells are defined."));
}
@Override
public boolean hasRecipeRemainder(final ItemStack stack) {
return AEConfig.instance().isFeatureEnabled(AEFeature.ENABLE_DISASSEMBLY_CRAFTING);
}
}
@@ -1,86 +0,0 @@
/*
* 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,88 @@
/*
* 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 java.util.List;
import alexiil.mc.lib.attributes.item.FixedItemInv;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemStack;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import appeng.api.AEApi;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.IMEInventoryHandler;
import appeng.api.storage.cells.ICellInventoryHandler;
import appeng.api.storage.cells.ICellWorkbenchItem;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.items.AEBaseItem;
import appeng.items.contents.CellConfig;
public class CreativeStorageCellItem extends AEBaseItem implements ICellWorkbenchItem {
public CreativeStorageCellItem(Settings props) {
super(props);
}
@Override
public boolean isEditable(final ItemStack is) {
return true;
}
@Override
public FixedItemInv getUpgradesInventory(final ItemStack is) {
return null;
}
@Override
public FixedItemInv getConfigInventory(final ItemStack is) {
return new CellConfig(is);
}
@Override
public FuzzyMode getFuzzyMode(final ItemStack is) {
return FuzzyMode.IGNORE_ALL;
}
@Override
public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {
}
@Environment(EnvType.CLIENT)
@Override
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
final IMEInventoryHandler<?> inventory = AEApi.instance().registries().cell().getCellInventory(stack, null,
AEApi.instance().storage().getStorageChannel(IItemStorageChannel.class));
if (inventory instanceof ICellInventoryHandler) {
final CellConfig cc = new CellConfig(stack);
for (final ItemStack is : cc) {
if (!is.isEmpty()) {
lines.add(is.getName());
}
}
}
}
}
@@ -1,153 +0,0 @@
/*
* 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.storage;
import java.util.List;
import net.fabricmc.api.EnvType;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.text.LiteralText;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.text.Text;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.fabricmc.api.Environment;
import appeng.api.implementations.TransitionResult;
import appeng.api.implementations.items.ISpatialStorageCell;
import appeng.api.storage.ISpatialDimension;
import appeng.api.util.WorldCoord;
import appeng.core.AELog;
import appeng.core.localization.GuiText;
import appeng.items.AEBaseItem;
import appeng.spatial.SpatialDimensionManager;
import appeng.spatial.StorageHelper;
public class SpatialStorageCellItem extends AEBaseItem implements ISpatialStorageCell {
private static final String TAG_DIMENSION_ID = "dimension_id";
private final int maxRegion;
public SpatialStorageCellItem(Settings props, final int spatialScale) {
super(props);
this.maxRegion = spatialScale;
}
@Environment(EnvType.CLIENT)
@Override
public void appendTooltip(final ItemStack stack, final World world, final List<Text> lines,
final TooltipContext advancedTooltips) {
final DimensionType dimType = this.getStoredDimension(stack);
if (dimType == null) {
lines.add(GuiText.Unformatted.textComponent().formatted(Formatting.ITALIC));
lines.add(GuiText.SpatialCapacity.textComponent(maxRegion, maxRegion, maxRegion));
} else {
SpatialDimensionManager.INSTANCE.addCellDimensionTooltip(dimType, lines);
}
if (advancedTooltips.isAdvanced()) {
if (dimType != null && dimType.getRegistryName() != null) {
lines.add(new LiteralText("Dimension: " + dimType.getRegistryName()));
}
}
}
@Override
public boolean isSpatialStorage(final ItemStack is) {
return true;
}
@Override
public int getMaxStoredDim(final ItemStack is) {
return this.maxRegion;
}
@Override
public DimensionType getStoredDimension(final ItemStack is) {
final CompoundTag c = is.getTag();
if (c != null && c.contains(TAG_DIMENSION_ID)) {
try {
Identifier dimTypeId = new Identifier(c.getString(TAG_DIMENSION_ID));
return DimensionType.byName(dimTypeId);
} catch (Exception e) {
AELog.warn("Failed to retrieve storage cell dimension.", e);
}
}
return null;
}
@Override
public TransitionResult doSpatialTransition(final ItemStack is, final ServerWorld w, final WorldCoord min,
final WorldCoord max, int playerId) {
final int targetX = max.x - min.x - 1;
final int targetY = max.y - min.y - 1;
final int targetZ = max.z - min.z - 1;
final int maxSize = this.getMaxStoredDim(is);
final BlockPos targetSize = new BlockPos(targetX, targetY, targetZ);
ISpatialDimension manager = SpatialDimensionManager.INSTANCE;
DimensionType storedDim = this.getStoredDimension(is);
if (storedDim == null) {
storedDim = manager.createNewCellDimension(targetSize);
}
if (storedDim == null) {
// Failed to create the dimension
return new TransitionResult(false, 0);
}
try {
if (manager.isCellDimension(storedDim)) {
ServerWorld cellWorld = manager.getWorld(storedDim);
BlockPos scale = manager.getCellDimensionSize(storedDim);
if (scale.equals(targetSize)) {
if (targetX <= maxSize && targetY <= maxSize && targetZ <= maxSize) {
BlockPos offset = manager.getCellDimensionOrigin(storedDim);
this.setStoredDimension(is, storedDim);
StorageHelper.getInstance().swapRegions(w, min.x + 1, min.y + 1, min.z + 1, cellWorld,
offset.getX(), offset.getY(), offset.getZ(), targetX - 1, targetY - 1, targetZ - 1);
return new TransitionResult(true, 0);
}
}
}
return new TransitionResult(false, 0);
} finally {
// clean up newly created dimensions that failed transfer
if (manager.isCellDimension(storedDim) && this.getStoredDimension(is) == null) {
manager.deleteCellDimension(storedDim);
}
}
}
private void setStoredDimension(final ItemStack is, DimensionType dim) {
final CompoundTag c = is.getOrCreateTag();
c.putString(TAG_DIMENSION_ID, dim.getRegistryName().toString());
}
}
@@ -1,138 +0,0 @@
/*
* 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());
}
}
@@ -1,175 +0,0 @@
/*
* 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.NBTUtil;
import net.minecraft.text.TranslatableText;
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.resultSuccess(p.getStackInHand(hand));
}
return TypedActionResult.resultPass(p.getStackInHand(hand));
}
@Override
public boolean itemInteractionForEntity(ItemStack is, final PlayerEntity player, final LivingEntity target,
final Hand hand) {
if (target instanceof PlayerEntity && !player.isInSneakingPose()) {
if (player.isCreative()) {
is = player.getStackInHand(hand);
}
this.encode(is, (PlayerEntity) target);
player.swingHand(hand);
return true;
}
return false;
}
@Override
public Text getName(final ItemStack is) {
final GameProfile username = this.getProfile(is);
return username != null ? super.getName(is).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();
NBTUtil.writeGameProfile(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 NBTUtil.readGameProfile(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 {
Text 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);
}
}
}
@@ -1,196 +0,0 @@
/*
* 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.resources.I18n;
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.util.math.BlockPos;
import net.minecraft.text.Text;
import net.minecraft.world.WorldView;
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 (I18n.hasKey(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 onItemUse(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.onItemUse(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);
}
@Override
public boolean doesSneakBypassUse(ItemStack stack, WorldView world, BlockPos pos, PlayerEntity player) {
return true;
}
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);
}
}
@@ -1,169 +0,0 @@
/*
* 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 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.TypedActionResult;
import net.minecraft.util.ActionResult;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.hit.HitResult;
import net.minecraft.world.WorldView;
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 {
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.isInside());
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;
}
@Override
public boolean doesSneakBypassUse(ItemStack stack, WorldView world, BlockPos pos, PlayerEntity player) {
return true;
}
public boolean serverSideToolLogic(ItemUsageContext useContext) {
BlockPos pos = useContext.getPos();
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)) {
if (bs.rotate(w, pos, Rotation.CLOCKWISE_90) != bs) {
bs.neighborUpdate(w, pos, Blocks.AIR, pos, false);
p.swingHand(hand);
return !w.isClient;
}
}
}
if (!p.isInSneakingPose()) {
if (p.openContainer 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;
}
}
@@ -1,167 +0,0 @@
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;
}
}
}
@@ -1,60 +0,0 @@
/*
* 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 hitEntity(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;
}
}
@@ -1,460 +0,0 @@
/*
* 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).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.getCollection().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);
}
}
@@ -1,41 +0,0 @@
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;
}
}
}
@@ -1,343 +0,0 @@
/*
* 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.util.FakePlayer;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.TNTBlock;
import net.minecraft.block.Material;
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.item.crafting.FurnaceRecipe;
import net.minecraft.recipe.RecipeType;
import net.minecraft.particle.ParticleTypes;
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.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_0_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.rand.nextFloat() - w.rand.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 hitEntity(final ItemStack item, final LivingEntity target, final LivingEntity hitter) {
if (this.getAECurrentPower(item) > 1600) {
this.extractAEPower(item, 1600, Actionable.MODULATE);
target.setFire(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.canPlayerEdit(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) {
w.removeBlock(pos, false);
block.catchFire(w.getBlockState(pos), w, pos, context.getSide(), p);
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<FurnaceRecipe> recipe = w.getRecipeManager().getRecipe(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.canPlayerEdit(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;
}
}
@@ -1,474 +0,0 @@
/*
* 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.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.hit.EntityHitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.Direction;
import net.minecraft.util.EntityDamageSource;
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.setFleeceColor(col.dye);
}
entityHit.damage(DamageSource.causePlayerDamage(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.getPos().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.knockBack(p, 0, -direction.x, -direction.z);
// el.knockBack( p, 0, Vec3d.x,
// Vec3d.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.getPos();
final BlockState bs = w.getBlockState(blockPos);
final float hardness = bs.getBlockHardness(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);
}
}
@@ -1,159 +0,0 @@
/*
* 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);
}
@Override
public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
return slotChanged;
}
}
@@ -1,130 +0,0 @@
/*
* 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 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.config.Actionable;
import appeng.api.config.SortDir;
import appeng.api.config.SortOrder;
import appeng.api.config.ViewItems;
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(Settings.SORT_BY, SortOrder.NAME);
out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL);
out.registerSetting(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);
}
@Override
public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
return slotChanged;
}
}
@@ -1,162 +0,0 @@
/*
* 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 net.minecraftforge.common.capabilities.ICapabilityProvider;
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()
.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);
}
}
@Override
public double getDurabilityForDisplay(final ItemStack is) {
return 1 - this.getAECurrentPower(is) / this.getAEMaxPower(is);
}
@Override
public boolean isDamaged(final ItemStack stack) {
return true;
}
@Override
public void setDamage(final ItemStack stack, final int damage) {
}
@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;
}
@Override
public ICapabilityProvider initCapabilities(ItemStack stack, CompoundTag nbt) {
return new PoweredItemCapabilities(stack, this);
}
}
@@ -1,92 +0,0 @@
/*
* 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.powersink;
import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.Direction;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.ICapabilityProvider;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.energy.IEnergyStorage;
import appeng.api.config.Actionable;
import appeng.api.config.PowerUnits;
import appeng.api.implementations.items.IAEItemPowerStorage;
import appeng.capabilities.Capabilities;
/**
* The capability provider to expose chargable items to other mods.
*/
class PoweredItemCapabilities implements ICapabilityProvider, IEnergyStorage {
private final ItemStack is;
private final IAEItemPowerStorage item;
PoweredItemCapabilities(ItemStack is, IAEItemPowerStorage item) {
this.is = is;
this.item = item;
}
@SuppressWarnings("unchecked")
@Override
public <T> LazyOptional<T> getCapability(Capability<T> capability, @Nullable Direction facing) {
if (capability == Capabilities.FORGE_ENERGY) {
return (LazyOptional<T>) LazyOptional.of(() -> this);
}
return LazyOptional.empty();
}
@Override
public int receiveEnergy(int maxReceive, boolean simulate) {
final double convertedOffer = PowerUnits.RF.convertTo(PowerUnits.AE, maxReceive);
final double overflow = this.item.injectAEPower(this.is, convertedOffer,
simulate ? Actionable.SIMULATE : Actionable.MODULATE);
return maxReceive - (int) PowerUnits.AE.convertTo(PowerUnits.RF, overflow);
}
@Override
public int extractEnergy(int maxExtract, boolean simulate) {
return 0;
}
@Override
public int getEnergyStored() {
return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.item.getAECurrentPower(this.is));
}
@Override
public int getMaxEnergyStored() {
return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.item.getAEMaxPower(this.is));
}
@Override
public boolean canExtract() {
return false;
}
@Override
public boolean canReceive() {
return true;
}
}
@@ -0,0 +1,41 @@
/*
* 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.quartz;
import net.minecraft.item.AxeItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolMaterials;
import appeng.api.features.AEFeature;
import appeng.util.Platform;
public class QuartzAxeItem extends AxeItem {
private final AEFeature type;
public QuartzAxeItem(Item.Settings props, final AEFeature type) {
super(ToolMaterials.IRON, 6.0F, -3.1F, props);
this.type = type;
}
@Override
public boolean canRepair(final ItemStack a, final ItemStack b) {
return Platform.canRepair(this.type, a, b);
}
}
@@ -0,0 +1,64 @@
/*
* 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.quartz;
import appeng.container.ContainerLocator;
import appeng.mixins.RemainderSetter;
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.world.World;
import appeng.api.features.AEFeature;
import appeng.api.implementations.guiobjects.IGuiItem;
import appeng.api.implementations.guiobjects.IGuiItemObject;
import appeng.items.AEBaseItem;
import appeng.util.Platform;
public class QuartzCuttingKnifeItem extends AEBaseItem implements IGuiItem {
private final AEFeature type;
public QuartzCuttingKnifeItem(Item.Settings props, final AEFeature type) {
super(props);
this.type = type;
// See below for reasoning
((RemainderSetter)this).setRecipeRemainder(this);
}
@Override
public TypedActionResult<ItemStack> use(final World w, final PlayerEntity p, final Hand hand) {
if (Platform.isServer()) {
// FIXME FABRIC ContainerOpener.openContainer(QuartzKnifeContainer.TYPE, p, ContainerLocator.forHand(p, hand));
throw new IllegalStateException();
}
p.swingHand(hand);
return new TypedActionResult<>(ActionResult.SUCCESS, p.getStackInHand(hand));
}
@Override
public IGuiItemObject getGuiObject(final ItemStack is, int playerInventorySlot, final World world,
final BlockPos pos) {
// FIXME FABRIC return new QuartzKnifeObj(is);
throw new IllegalStateException();
}
}
@@ -0,0 +1,42 @@
/*
* 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.quartz;
import net.minecraft.item.HoeItem;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolMaterials;
import appeng.api.features.AEFeature;
import appeng.util.Platform;
public class QuartzHoeItem extends HoeItem {
private final AEFeature type;
public QuartzHoeItem(Item.Settings props, final AEFeature type) {
super(ToolMaterials.IRON, -2, -1.0F, props);
this.type = type;
}
@Override
public boolean canRepair(final ItemStack a, final ItemStack b) {
return Platform.canRepair(this.type, a, b);
}
}
@@ -0,0 +1,41 @@
/*
* 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.quartz;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolMaterials;
import net.minecraft.item.PickaxeItem;
import appeng.api.features.AEFeature;
import appeng.util.Platform;
public class QuartzPickaxeItem extends PickaxeItem {
private final AEFeature type;
public QuartzPickaxeItem(Item.Settings props, final AEFeature type) {
super(ToolMaterials.IRON, 1, -2.8F, props);
this.type = type;
}
@Override
public boolean canRepair(final ItemStack a, final ItemStack b) {
return Platform.canRepair(this.type, a, b);
}
}
@@ -0,0 +1,41 @@
/*
* 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.quartz;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolMaterials;
import net.minecraft.item.ShovelItem;
import appeng.api.features.AEFeature;
import appeng.util.Platform;
public class QuartzSpadeItem extends ShovelItem {
private final AEFeature type;
public QuartzSpadeItem(Item.Settings props, final AEFeature type) {
super(ToolMaterials.IRON, 1.5F, -3.0F, props);
this.type = type;
}
@Override
public boolean canRepair(final ItemStack a, final ItemStack b) {
return Platform.canRepair(this.type, a, b);
}
}
@@ -0,0 +1,41 @@
/*
* 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.quartz;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ToolMaterials;
import net.minecraft.item.SwordItem;
import appeng.api.features.AEFeature;
import appeng.util.Platform;
public class QuartzSwordItem extends SwordItem {
private final AEFeature type;
public QuartzSwordItem(Item.Settings props, AEFeature type) {
super(ToolMaterials.IRON, 3, -2.4F, props);
this.type = type;
}
@Override
public boolean canRepair(final ItemStack a, final ItemStack b) {
return Platform.canRepair(this.type, a, b);
}
}
@@ -0,0 +1,69 @@
/*
* 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.quartz;
import appeng.hooks.AEToolItem;
import net.minecraft.block.Block;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.util.ActionResult;
import net.minecraft.util.math.BlockPos;
import appeng.api.implementations.items.IAEWrench;
import appeng.api.util.DimensionalCoord;
import appeng.block.AEBaseBlock;
import appeng.items.AEBaseItem;
import appeng.util.Platform;
public class QuartzWrenchItem extends AEBaseItem implements IAEWrench, AEToolItem {
public QuartzWrenchItem(Item.Settings props) {
super(props);
}
@Override
public ActionResult onItemUseFirst(ItemStack stack, ItemUsageContext context) {
if (!context.getPlayer().isInSneakingPose() && Platform
.hasPermissions(new DimensionalCoord(context.getWorld(), context.getBlockPos()), context.getPlayer())) {
Block block = context.getWorld().getBlockState(context.getBlockPos()).getBlock();
if (block instanceof AEBaseBlock) {
if (Platform.isClient()) {
// TODO 1.10-R - if we return FAIL on client, action will not be sent to server.
// Fix that in all Block#onItemUseFirst overrides.
return !context.getWorld().isClient ? ActionResult.SUCCESS : ActionResult.PASS;
}
AEBaseBlock aeBlock = (AEBaseBlock) block;
if (aeBlock.rotateAroundFaceAxis(context.getWorld(), context.getBlockPos(), context.getSide())) {
context.getPlayer().swingHand(context.getHand());
return !context.getWorld().isClient ? ActionResult.SUCCESS : ActionResult.FAIL;
}
}
}
return ActionResult.PASS;
}
@Override
public boolean canWrench(final ItemStack wrench, final PlayerEntity player, final BlockPos pos) {
return true;
}
}