feat: client only

This commit is contained in:
Discreater committed 2021-04-30 23:53:58 +08:00
1 parent 5bbc857407
commit 477a84804e
39 files changed
+846 -1102

No files matched your search

@@ -1,5 +1,7 @@
package me.towdium.jecalculation;
import codechicken.core.CommonUtils;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
@@ -7,6 +9,10 @@ import net.minecraftforge.common.config.Property;
import java.io.File;
public class JecaConfig {
public static File configDir = new File(Loader.instance().getConfigDir(), "JustEnoughCalculation/");
public static final File configFile = new File(configDir, "main.cfg");
public static final File recordFile = new File(configDir, "record.data");
public static boolean initialized = false;
public static Configuration config;
@@ -123,8 +129,7 @@ public class JecaConfig {
public static Object empty;
public static void preInit(FMLPreInitializationEvent event) {
config = new Configuration(new File(event.getModConfigurationDirectory(), "JustEnoughCalculation" + ".cfg"),
JustEnoughCalculation.Reference.VERSION);
config = new Configuration(configFile, JustEnoughCalculation.Reference.VERSION);
config.load();
handleInit();
config.save();
@@ -1,21 +1,17 @@
package me.towdium.jecalculation;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkCheckHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.nei.NEIPlugin;
import me.towdium.jecalculation.network.IProxy;
import me.towdium.jecalculation.network.ClientHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Map;
/**
* @author Towdium
@@ -23,6 +19,7 @@ import java.util.Map;
@ParametersAreNonnullByDefault
@SuppressWarnings("unused")
@SideOnly(Side.CLIENT)
@Mod(modid = JustEnoughCalculation.Reference.MODID,
name = JustEnoughCalculation.Reference.MODNAME,
version = JustEnoughCalculation.Reference.VERSION,
@@ -31,42 +28,25 @@ public class JustEnoughCalculation {
@Mod.Instance(Reference.MODID)
public static JustEnoughCalculation INSTANCE;
@SidedProxy(modId = Reference.MODID,
clientSide = "me.towdium.jecalculation.network.ProxyClient",
serverSide = "me.towdium.jecalculation.network.ProxyServer")
public static IProxy proxy;
public static ClientHandler handler = new ClientHandler();
public static SimpleNetworkWrapper network;
public static Logger logger = LogManager.getLogger(Reference.MODID);
public static enumSide side = enumSide.UNDEFINED;
@NetworkCheckHandler
public static boolean networkCheck(Map<String, String> mods, Side s) {
if (s == Side.SERVER) {
if (mods.containsKey(Reference.MODID) && !JecaConfig.isClintMode()) {
side = enumSide.BOTH;
} else {
side = enumSide.CLIENT;
}
return true;
} else return mods.containsKey(Reference.MODID);
}
public static enumSide side = enumSide.CLIENT;
@Mod.EventHandler
public static void initPre(FMLPreInitializationEvent event) {
JecaConfig.preInit(event);
network = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MODID);
proxy.initPre();
handler.initPre();
}
@Mod.EventHandler
public static void init(FMLInitializationEvent event) {
proxy.init();
handler.init();
}
@Mod.EventHandler
public static void postInit(FMLPostInitializationEvent event) {
proxy.initPost();
handler.initPost();
NEIPlugin.init();
}
@@ -27,6 +27,7 @@ public class CostList {
});
}
@SuppressWarnings("UnusedReturnValue")
public CostList merge(CostList costList, boolean add) {
costList.labels.forEach(i -> labels.add(add ? i.copy() : i.copy().invertAmount()));
return cancel();
@@ -0,0 +1,113 @@
package me.towdium.jecalculation.data;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.JecaConfig;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.data.structure.Recents;
import me.towdium.jecalculation.data.structure.Recipe;
import me.towdium.jecalculation.data.structure.Recipes;
import me.towdium.jecalculation.utils.wrappers.Triple;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Author: towdium
* Date: 17-10-15.
*/
@SideOnly(Side.CLIENT)
public class ControllerClient {
public static final String KEY_RECIPES = "recipes";
public static final String KEY_RECENTS = "recents";
static Recipes recipesClient;
static Recents recentsClient;
static Recipes getRecord() {
return recipesClient;
}
public static List<String> getGroups() {
Recipes user = getRecord();
if (user.size() != 0)
return user.stream().map(Map.Entry::getKey).collect(Collectors.toList());
else
return new ArrayList<>();
}
public static void addRecipe(String group, Recipe recipe) {
getRecord().add(group, recipe);
writeToLocal();
}
public static void setRecipe(String group, int index, Recipe recipe) {
getRecord().set(group, index, recipe);
writeToLocal();
}
public static void removeRecipe(String group, int index) {
getRecord().remove(group, index);
writeToLocal();
}
public static Recipe getRecipe(String group, int index) {
return getRecord().getRecipe(group, index);
}
public static List<Triple<Recipe, String, Integer>> getRecipes() {
return getRecord().getRecipes();
}
public static List<Triple<Recipe, String, Integer>> getRecipes(String group) {
return getRecord().getRecipes(group);
}
public static List<Triple<Recipe, String, Integer>> getRecipes(ILabel label, Recipe.enumIoType type) {
return getRecord().getRecipes(label, type);
}
public static List<ILabel> getRecent() {
return recentsClient.getRecords();
}
public static void setRecent(ILabel label) {
recentsClient.push(label);
writeToLocal();
}
public static void loadFromLocal() {
try {
File file = JecaConfig.recordFile;
FileInputStream stream = new FileInputStream(file);
NBTTagCompound nbt = CompressedStreamTools.readCompressed(stream);
recipesClient = nbt.hasKey(KEY_RECIPES) ? new Recipes(nbt.getTagList(KEY_RECIPES, 10)) : new Recipes();
recentsClient = nbt.hasKey(KEY_RECENTS) ? new Recents(nbt.getTagList(KEY_RECENTS, 10)) : new Recents();
} catch (IOException e) {
e.printStackTrace();
recipesClient = new Recipes();
recentsClient = new Recents();
}
}
public static void writeToLocal() {
try {
File file = JecaConfig.recordFile;
NBTTagCompound nbt = new NBTTagCompound();
nbt.setTag(KEY_RECENTS, recentsClient.serialize());
nbt.setTag(KEY_RECIPES, recipesClient.serialize());
FileOutputStream stream = new FileOutputStream(file);
CompressedStreamTools.writeCompressed(nbt, stream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,39 @@
package me.towdium.jecalculation.data.capacity;
import me.towdium.jecalculation.JustEnoughCalculation;
import me.towdium.jecalculation.data.structure.Recipes;
import net.minecraft.entity.Entity;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
@Deprecated
public class JecaCapabilityProvider implements IExtendedEntityProperties {
public final static String PROPERTIES_NAME = JustEnoughCalculation.Reference.MODID + ".record";
public Recipes record;
protected Entity theEntity;
protected World theWorld;
public JecaCapabilityProvider(Recipes record) {
this.record = record;
}
@Override
public void saveNBTData(NBTTagCompound compound) {
JustEnoughCalculation.logger.info("ExtendedProperties save NBTData()");
}
@Override
public void loadNBTData(NBTTagCompound compound) {
JustEnoughCalculation.logger.info("ExtendedProperties load NBTData()");
}
@Override
public void init(Entity entity, World world) {
JustEnoughCalculation.logger.info("ExtendedProperties init()");
this.theEntity = entity;
this.theWorld = world;
}
}
@@ -12,6 +12,7 @@ import me.towdium.jecalculation.data.label.labels.LOreDict;
import me.towdium.jecalculation.data.label.labels.LString;
import me.towdium.jecalculation.polyfill.mc.client.renderer.GlStateManager;
import me.towdium.jecalculation.utils.ItemStackHelper;
import me.towdium.jecalculation.utils.Utilities;
import me.towdium.jecalculation.utils.Utilities.Relation;
import me.towdium.jecalculation.utils.Utilities.ReversedIterator;
import me.towdium.jecalculation.utils.wrappers.Pair;
@@ -53,6 +54,18 @@ public interface ILabel {
ILabel invertAmount();
static void initClient() {
CONVERTER.register(LOreDict::guess);
EDITOR.register(PickerSimple.FluidStack::new, "fluid_stack", new LFluidStack(1000, FluidRegistry.WATER));
EDITOR.register(PickerSimple.OreDict::new, "ore_dict", new LOreDict("ingotIron"));
EDITOR.register(PickerUniversal::new, "string", new LString("example", 1));
MERGER.register("itemStack", "itemStack", LItemStack::merge);
MERGER.register("oreDict", "oreDict", LOreDict::mergeOreDict);
}
int getAmount();
String getAmountString();
@SideOnly(Side.CLIENT)
@@ -72,14 +85,7 @@ public interface ILabel {
NBTTagCompound toNBTTagCompound();
static void initClient() {
CONVERTER.register(LOreDict::guess);
EDITOR.register(PickerSimple.FluidStack::new, "fluid_stack", new LFluidStack(FluidRegistry.WATER, 1000));
EDITOR.register(PickerSimple.OreDict::new, "ore_dict", new LOreDict("ingotIron"));
EDITOR.register(PickerUniversal::new, "string", new LString("example", 1));
MERGER.register("itemStack", "itemStack", Merger::mergeItemStackNItemStack);
MERGER.register("oreDict", "oreDict", Merger::mergeOreDictNOreDict);
}
void setAmount(int amount);
String getIdentifier();
@@ -112,34 +118,6 @@ public interface ILabel {
functions.add(a, b, func);
}
static Optional<ILabel> mergeItemStackNItemStack(ILabel a, ILabel b, boolean add) {
if (a instanceof LItemStack && b instanceof LItemStack) {
LItemStack lisA = (LItemStack) a;
LItemStack lisB = (LItemStack) b;
ItemStack isA = lisA.getItemStack();
ItemStack isB = lisB.getItemStack();
if (isA.getItem() == isB.getItem() && isA.getItemDamage() == isB.getItemDamage() &&
(isA.getTagCompound() == null ? !isB.hasTagCompound() :
isA.getTagCompound().equals(isB.getTagCompound()))) {
LItemStack ret = new LItemStack(lisA.getItemStack(),
add ? lisA.getAmount() + lisB.getAmount() : lisA.getAmount() - lisB.getAmount());
return Optional.of(ret.getAmount() == 0 ? ILabel.EMPTY : ret);
}
}
return Optional.empty();
}
static Optional<ILabel> mergeOreDictNOreDict(ILabel a, ILabel b, boolean add) {
if (a instanceof LOreDict && b instanceof LOreDict) {
LOreDict lodA = (LOreDict) a;
LOreDict lodB = (LOreDict) b;
if (lodA.getName().equals(lodB.getName()))
return Optional.of(new LOreDict(lodA.getName(),
add ? lodA.getAmount() + lodB.getAmount() : lodA.getAmount() - lodB.getAmount()));
}
return Optional.empty();
}
public Optional<Pair<ILabel, ILabel>> merge(ILabel a, ILabel b, boolean add) {
Optional<ILabel> ret = functions.get(a.getIdentifier(), b.getIdentifier())
.orElse((x, y, f) -> Optional.empty()).merge(a, b, add);
@@ -194,7 +172,6 @@ public interface ILabel {
*/
public ILabel deserialize(NBTTagCompound nbt) {
String s = nbt.getString(KEY_IDENTIFIER);
ILabel e = idToData.get(s).apply(nbt.getCompoundTag(KEY_CONTENT));
return idToData.get(s).apply(nbt.getCompoundTag(KEY_CONTENT));
}
@@ -291,6 +268,16 @@ public interface ILabel {
return this;
}
@Override
public int getAmount() {
return 0;
}
@Override
public void setAmount(int amount) {
}
@Override
public String getAmountString() {
return "";
@@ -325,4 +312,97 @@ public interface ILabel {
public void drawLabel(JecaGui gui) {
}
}
abstract class Impl implements ILabel {
public static final String KEY_AMOUNT = "amount";
protected int amount;
public Impl(int amount) {
this.amount = amount;
}
public Impl(Impl lsa) {
this(lsa.amount);
}
public Impl(NBTTagCompound nbt) {
amount = nbt.getInteger(KEY_AMOUNT);
}
protected int getMultiplier() {
return 1;
}
@Override
public ILabel increaseAmount() {
setAmount(getAmount() + getMultiplier());
return this;
}
@Override
public ILabel increaseAmountLarge() {
setAmount(getAmount() + 10 * getMultiplier());
return this;
}
@Override
public ILabel decreaseAmount() {
if (getAmount() <= getMultiplier()) return ILabel.EMPTY;
else {
setAmount(getAmount() - getMultiplier());
return this;
}
}
@Override
public ILabel decreaseAmountLarge() {
if (getAmount() <= 10 * getMultiplier()) return ILabel.EMPTY;
else {
setAmount(getAmount() - 10 * getMultiplier());
return this;
}
}
@Override
public ILabel invertAmount() {
setAmount(-getAmount());
return this;
}
@Override
@SideOnly(Side.CLIENT)
public List<String> getToolTip(List<String> existing, boolean detailed) {
if (detailed) existing.add(FORMAT_GREY +
Utilities.I18n.format("label.common.tooltip.amount", Integer.toString(getAmount())));
return existing;
}
@Override
public NBTTagCompound toNBTTagCompound() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger(KEY_AMOUNT, amount);
return nbt;
}
@Override
public int getAmount() {
return amount;
}
@Override
public void setAmount(int amount) {
this.amount = amount;
}
@Override
@SideOnly(Side.CLIENT)
public String getAmountString() {
return getAmount() == 0 ? "" : Utilities.cutNumber(getAmount(), 5);
}
@Override
public boolean equals(Object obj) {
return obj instanceof Impl && amount == ((Impl) obj).amount;
}
}
}
@@ -8,70 +8,70 @@ import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.utils.Utilities;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
import java.util.Objects;
/**
* Author: towdium
* Date: 17-9-27.
*/
@ParametersAreNonnullByDefault
public class LFluidStack implements ILabel {
public class LFluidStack extends ILabel.Impl {
public static final String IDENTIFIER = "fluidStack";
public static final String KEY_FLUID = "name";
public static final String KEY_FLUID = "fluid";
public static final String KEY_NBT = "nbt";
FluidStack fluid;
Fluid fluid;
NBTTagCompound nbt;
FluidStack temp;
public LFluidStack(FluidStack fluid) {
this.fluid = fluid;
public LFluidStack(FluidStack fs) {
this(fs.amount, fs.getFluid(), fs.tag);
}
public LFluidStack(Fluid fluid, int amount) {
this.fluid = new FluidStack(fluid, amount);
public LFluidStack(int amount, Fluid fluid) {
this(amount, fluid, null);
}
public LFluidStack(int amount, Fluid fluid, @Nullable NBTTagCompound nbt) {
super(amount);
this.fluid = fluid;
this.nbt = nbt;
temp = new FluidStack(fluid, amount, nbt);
}
public LFluidStack(NBTTagCompound nbt) {
fluid = FluidStack.loadFluidStackFromNBT(nbt.getCompoundTag(KEY_FLUID));
this(nbt.getInteger(KEY_AMOUNT), Objects.requireNonNull(FluidRegistry.getFluid(nbt.getString(KEY_FLUID))),
nbt.hasKey(KEY_NBT) ? nbt.getCompoundTag(KEY_NBT) : null);
}
public LFluidStack(LFluidStack lfs) {
super(lfs);
fluid = lfs.fluid;
nbt = lfs.nbt;
temp = lfs.temp;
}
@Override
public ILabel increaseAmount() {
return ILabel.EMPTY;
}
@Override
public ILabel increaseAmountLarge() {
return ILabel.EMPTY;
}
@Override
public ILabel decreaseAmount() {
return ILabel.EMPTY;
}
@Override
public ILabel decreaseAmountLarge() {
return ILabel.EMPTY;
}
@Override
public ILabel invertAmount() {
fluid.amount *= -1;
return this;
protected int getMultiplier() {
return 100;
}
@Override
public String getAmountString() {
return fluid.amount >= 1000 ? Utilities.cutNumber(fluid.amount / 1000f, 4) + "B"
: Integer.toString(fluid.amount) + "mB";
return amount >= 1000 ? Utilities.cutNumber(amount / 1000f, 4) + "B"
: Integer.toString(amount) + "mB";
}
@Override
@SideOnly(Side.CLIENT)
public String getDisplayName() {
return fluid.getLocalizedName();
return temp.getLocalizedName();
}
@Override
@@ -81,28 +81,32 @@ public class LFluidStack implements ILabel {
@Override
public ILabel copy() {
return new LFluidStack(fluid);
return new LFluidStack(this);
}
@Override
public NBTTagCompound toNBTTagCompound() {
NBTTagCompound ret = new NBTTagCompound();
ret.setTag(KEY_FLUID, fluid.writeToNBT(new NBTTagCompound())); // TODO check
NBTTagCompound ret = super.toNBTTagCompound();
ret.setString(KEY_FLUID, FluidRegistry.getFluidName(fluid));
ret.setTag(KEY_NBT, nbt);
return ret;
}
@Override
@SideOnly(Side.CLIENT)
public List<String> getToolTip(List<String> existing, boolean detailed) {
if (detailed) existing.add(FORMAT_GREY +
Utilities.I18n.format("label.common.tooltip.amount", Integer.toString(getAmount())) + "mB");
existing.add(FORMAT_BLUE + FORMAT_ITALIC + Utilities.getModName(fluid));
return existing;
}
@Override
@SideOnly(Side.CLIENT)
public void drawLabel(JecaGui gui) {
gui.drawResource(Resource.LBL_FLUID, 0, 0);
gui.drawFluid(fluid.getFluid(), 2, 2, 12, 12);
gui.drawFluid(fluid, 2, 2, 12, 12);
}
@Override
@@ -2,58 +2,98 @@ package me.towdium.jecalculation.data.label.labels;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.utils.Utilities;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.oredict.OreDictionary;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Author: towdium
* Date: 8/11/17.
*/
@ParametersAreNonnullByDefault
public class LItemStack extends LabelSimpleAmount {
public class LItemStack extends ILabel.Impl {
public static final String IDENTIFIER = "itemStack";
public static final String KEY_STACK = "stack";
public static final String KEY_ITEM = "item";
public static final String KEY_META = "meta";
public static final String KEY_NBT = "nbt";
ItemStack itemStack;
Item item;
int meta;
NBTTagCompound nbt;
transient ItemStack temp;
public LItemStack(ItemStack is) {
this(is, is.stackSize);
public LItemStack(int amount, Item item, int meta, @Nullable NBTTagCompound nbt) {
super(amount);
this.item = item;
this.meta = meta;
this.nbt = nbt == null ? null : (NBTTagCompound) nbt.copy();
temp = new ItemStack(item, 1, meta);
temp.setTagCompound(nbt);
}
// I will copy it!
public LItemStack(ItemStack is, int amount) {
super(amount);
itemStack = is.copy();
// Convert from itemStack
public LItemStack(ItemStack is) {
this(is.stackSize, is.getItem(), is.getItemDamage(), is.getTagCompound());
}
public LItemStack(NBTTagCompound nbt) {
super(nbt);
itemStack = ItemStack.loadItemStackFromNBT(nbt.getCompoundTag(KEY_STACK));
this(nbt.getInteger(KEY_AMOUNT), Objects.requireNonNull(Item.getItemById(nbt.getInteger(KEY_ITEM))),
nbt.getInteger(KEY_META), nbt.hasKey(KEY_NBT) ? nbt.getCompoundTag(KEY_NBT) : null);
}
private LItemStack(LItemStack lis) {
super(lis);
itemStack = lis.itemStack;
item = lis.item;
meta = lis.meta;
nbt = lis.nbt;
temp = new ItemStack(item, 1, meta);
temp.setTagCompound(nbt);
}
public static Optional<ILabel> merge(ILabel a, ILabel b, boolean add) {
if (a instanceof LItemStack && b instanceof LItemStack) {
LItemStack lisA = (LItemStack) a;
LItemStack lisB = (LItemStack) b;
boolean wildcard = lisA.meta == OreDictionary.WILDCARD_VALUE || lisB.meta == OreDictionary.WILDCARD_VALUE;
if ((Objects.equals(lisA.nbt, lisB.nbt)) &&
(lisA.meta == lisB.meta || wildcard)) {
LItemStack ret = new LItemStack(lisA);
if (wildcard)
ret.meta = OreDictionary.WILDCARD_VALUE;
ret.amount = add ? lisA.amount + lisB.amount : lisA.amount - lisB.amount;
return Optional.of(ret.amount == 0 ? ILabel.EMPTY : ret);
}
}
return Optional.empty();
}
public ItemStack getRep() {
return temp;
}
@Override
@SideOnly(Side.CLIENT)
public List<String> getToolTip(List<String> existing, boolean detailed) {
super.getToolTip(existing, detailed);
existing.add(FORMAT_BLUE + FORMAT_ITALIC + Utilities.getModName(itemStack));
existing.add(FORMAT_BLUE + FORMAT_ITALIC + Utilities.getModName(item));
return existing;
}
@Override
@SideOnly(Side.CLIENT)
public String getDisplayName() {
return itemStack.getItem() == null ? "" : itemStack.getDisplayName();
return temp.getItem() == null ? "" : temp.getDisplayName();
}
@Override
@@ -68,33 +108,34 @@ public class LItemStack extends LabelSimpleAmount {
@Override
public NBTTagCompound toNBTTagCompound() {
NBTTagCompound ret = new NBTTagCompound();
ret.setTag(KEY_STACK, itemStack.writeToNBT(new NBTTagCompound()));
ret.setInteger(KEY_AMOUNT, amount);
if (item == null)
return ILabel.EMPTY.toNBTTagCompound();
int id = Item.getIdFromItem(item);
NBTTagCompound ret = super.toNBTTagCompound();
ret.setInteger(KEY_META, meta);
ret.setInteger(KEY_ITEM, id);
if (nbt != null)
ret.setTag(KEY_NBT, nbt);
return ret;
}
@Override
@SideOnly(Side.CLIENT)
public void drawLabel(JecaGui gui) {
gui.drawItemStack(0, 0, itemStack, false);
gui.drawItemStack(0, 0, temp, false);
}
@Override
public boolean equals(Object obj) {
return obj instanceof LItemStack
&& ItemStack.areItemStacksEqual(itemStack, ((LItemStack) obj).itemStack)
&& amount == ((LItemStack) obj).amount;
if (obj instanceof LItemStack) {
LItemStack lis = (LItemStack) obj;
return super.equals(obj) && lis.item == item && lis.meta == meta && Objects.equals(nbt, lis.nbt);
} else
return false;
}
@Override
public int hashCode() {
return itemStack.getItemDamage() ^ itemStack.getItem().getUnlocalizedName().hashCode() ^ amount
^ (itemStack.getTagCompound() == null ? 0 : itemStack.getTagCompound().hashCode());
}
public ItemStack getItemStack() {
return itemStack;
return meta ^ item.getUnlocalizedName().hashCode() ^ (nbt == null ? 0 : nbt.hashCode());
}
}
@@ -18,6 +18,7 @@ import javax.annotation.ParametersAreNonnullByDefault;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
@@ -25,11 +26,11 @@ import java.util.stream.Collectors;
* Date: 17-9-10.
*/
@ParametersAreNonnullByDefault
public class LOreDict extends LabelSimpleAmount {
public class LOreDict extends ILabel.Impl {
public static final String IDENTIFIER = "oreDict";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final boolean MODE_FORCE = false;
public static final boolean MODE_FORCE = true;
protected String name;
@@ -58,31 +59,64 @@ public class LOreDict extends LabelSimpleAmount {
return Utilities.I18n.format("label.ore_dict.name", name);
}
public static Optional<ILabel> mergeOreDict(ILabel a, ILabel b, boolean add) {
if (a instanceof LOreDict && b instanceof LOreDict) {
LOreDict lodA = (LOreDict) a;
LOreDict lodB = (LOreDict) b;
if (lodA.getName().equals(lodB.getName()))
return Optional.of(new LOreDict(lodA.getName(),
add ? lodA.getAmount() + lodB.getAmount() : lodA.getAmount() - lodB.getAmount()));
}
return Optional.empty();
}
public static List<ILabel> guess(List<ILabel> iss) {
ILabel l = iss.get(0);
if ((MODE_FORCE || iss.size() > 1) && l instanceof LItemStack) {
HashSet<Integer> ids = new HashSet<>();
int amount = ((LItemStack) l).getAmount();
for (int i : OreDictionary.getOreIDs(((LItemStack) l).itemStack))
if (check(i, iss)) ids.add(i);
return ids.stream().map(i -> new LOreDict(OreDictionary.getOreName(i), amount))
.collect(Collectors.toList());
} else return new ArrayList<>();
HashSet<Integer> ids = new HashSet<>();
int amount = l.getAmount();
for (int i : OreDictionary.getOreIDs(((LItemStack) l).getRep()))
if (check(i, iss)) ids.add(i);
return ids.stream().map(i -> new LOreDict(OreDictionary.getOreName(i), amount))
.collect(Collectors.toList());
}
// check labels in the list suitable for the ore id
private static boolean check(int id, List<ILabel> labels) {
List<ItemStack> ores = OreDictionary.getOres(OreDictionary.getOreName(id));
for (ItemStack ore : ores) if (!check(ore, labels)) return false;
return true;
}
ArrayList<ItemStack> ores = OreDictionary.getOres(OreDictionary.getOreName(id));
if (labels.size() == 1 && ores.size() == 1
&& (ores.get(0).getItemDamage() == OreDictionary.WILDCARD_VALUE || !MODE_FORCE))
return false;
// check the recorded ore item is in the list
private static boolean check(ItemStack ore, List<ILabel> labels) {
for (ILabel label : labels)
if (label instanceof LItemStack && OreDictionary.itemMatches(ore, ((LItemStack) label).itemStack, false))
return true;
return false;
boolean acceptable = true;
for (ItemStack ore : ores) {
boolean found = false;
for (ILabel label : labels) {
if (label instanceof LItemStack && OreDictionary.itemMatches(
ore, ((LItemStack) label).getRep(), false)) {
found = true;
break;
}
}
if (!found) {
acceptable = false;
break;
}
}
for (ILabel label : labels) {
boolean found = false;
for (ItemStack ore : ores) {
if (label instanceof LItemStack && OreDictionary.itemMatches(
ore, ((LItemStack) label).getRep(), false)) {
found = true;
break;
}
}
if (!found) {
acceptable = false;
break;
}
}
return acceptable;
}
@Override
@@ -15,7 +15,7 @@ import javax.annotation.ParametersAreNonnullByDefault;
* Date: 17-9-28.
*/
@ParametersAreNonnullByDefault
public class LString extends LabelSimpleAmount {
public class LString extends ILabel.Impl {
public static final String KEY_NAME = "name";
public static final String IDENTIFIER = "string";
@@ -1,94 +0,0 @@
package me.towdium.jecalculation.data.label.labels;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.utils.Utilities;
import net.minecraft.nbt.NBTTagCompound;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
/**
* Author: towdium
* Date: 17-9-11.
*/
@ParametersAreNonnullByDefault
public abstract class LabelSimpleAmount implements ILabel {
public static final String KEY_AMOUNT = "amount";
protected int amount;
public LabelSimpleAmount(int amount) {
this.amount = amount;
}
public LabelSimpleAmount(LabelSimpleAmount lsa) {
this(lsa.amount);
}
public LabelSimpleAmount(NBTTagCompound nbt) {
amount = nbt.getInteger(KEY_AMOUNT);
}
@Override
public ILabel increaseAmount() {
amount++;
return this;
}
@Override
public ILabel increaseAmountLarge() {
amount += 10;
return this;
}
@Override
public ILabel decreaseAmount() {
if (amount <= 1) return ILabel.EMPTY;
else {
amount--;
return this;
}
}
@Override
public ILabel decreaseAmountLarge() {
if (amount <= 10) return ILabel.EMPTY;
else {
amount -= 10;
return this;
}
}
@Override
public ILabel invertAmount() {
amount *= -1;
return this;
}
@Override
@SideOnly(Side.CLIENT)
public List<String> getToolTip(List<String> existing, boolean detailed) {
if (detailed) existing.add(FORMAT_GREY +
Utilities.I18n.format("label.common.tooltip.amount", Integer.toString(amount)));
return existing;
}
@Override
@SideOnly(Side.CLIENT)
public String getAmountString() {
return amount == 0 ? "" : Utilities.cutNumber(amount, 5);
}
@Override
public NBTTagCompound toNBTTagCompound() {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger(KEY_AMOUNT, amount);
return nbt;
}
public int getAmount() {
return amount;
}
}
@@ -0,0 +1,45 @@
package me.towdium.jecalculation.data.structure;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.polyfill.NBTHelper;
import me.towdium.jecalculation.utils.Utilities;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class Recents {
public static final String IDENTIFIER = "recent";
Utilities.Recent<ILabel> record = new Utilities.Recent<>((a, b) -> a == ILabel.EMPTY || a.equals(b), 9);
public Recents(NBTTagList nbt) {
List<ILabel> ls = StreamSupport.stream(NBTHelper.spliterator(nbt), false)
.filter(n -> n instanceof NBTTagCompound)
.map(n -> ILabel.DESERIALIZER.deserialize((NBTTagCompound) n))
.collect(Collectors.toList());
new Utilities.ReversedIterator<>(ls).forEachRemaining(l -> record.push(l));
}
public Recents() {
}
public void push(ILabel label) {
record.push(label);
}
public ILabel getLatest() {
return record.toList().get(0);
}
public List<ILabel> getRecords() {
return record.toList();
}
public NBTTagList serialize() {
NBTTagList ret = new NBTTagList();
record.toList().forEach(l -> ret.appendTag(ILabel.DESERIALIZER.serialize(l)));
return ret;
}
}
@@ -48,9 +48,9 @@ public class Recipe {
for (int j = ls.length; j < i; j++) ret[j] = ILabel.EMPTY;
return ret;
};
this.input = convert.apply(input, 14);
this.catalyst = convert.apply(catalyst, 7);
this.output = convert.apply(output, 7);
this.input = convert.apply(input, 16);
this.catalyst = convert.apply(catalyst, 8);
this.output = convert.apply(output, 8);
Wrapper<Integer> hash = new Wrapper<>(0);
Consumer<ILabel[]> hasher = (ls) -> Arrays.stream(ls)
@@ -86,6 +86,12 @@ public class Recipe {
}
}
public ILabel getRep() {
for (int i = 0; i < 8; i++)
if (output[i] != ILabel.EMPTY) return output[i];
return ILabel.EMPTY;
}
public NBTTagCompound serialize() {
NBTTagCompound ret = new NBTTagCompound();
Function<ILabel[], NBTTagList> convert = (ls) -> {
@@ -0,0 +1,130 @@
package me.towdium.jecalculation.data.structure;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.polyfill.NBTHelper;
import me.towdium.jecalculation.utils.wrappers.Triple;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class Recipes {
public static final String KEY_NAME = "name";
public static final String KEY_CONTENT = "content";
LinkedHashMap<String, List<Recipe>> records = new LinkedHashMap<>();
public Recipes() {
}
public Recipes(NBTTagList nbt) {
deserialize(nbt);
}
public void deserialize(NBTTagList nbt) {
StreamSupport.stream(NBTHelper.spliterator(nbt), false).filter(g -> g instanceof NBTTagCompound).forEach(g -> {
NBTTagCompound group = (NBTTagCompound) g;
String name = group.getString(KEY_NAME);
NBTTagList recipes = group.getTagList(KEY_CONTENT, 10);
StreamSupport.stream(NBTHelper.spliterator(recipes), false).filter(r -> r instanceof NBTTagCompound)
.map(r -> (NBTTagCompound) r).forEach(r -> add(name, new Recipe(r)));
});
}
public void add(String group, Recipe recipe) {
if (records.containsKey(group)) {
records.get(group).add(recipe);
} else {
ArrayList<Recipe> l = new ArrayList<>();
l.add(recipe);
records.put(group, l);
}
}
public void modify(String group, int index, @Nullable Recipe recipe) {
if (index == -1) add(group, recipe);
else if (recipe == null) remove(group, index);
else set(group, index, recipe);
}
public void set(String group, int index, Recipe recipe) {
records.get(group).set(index, recipe);
}
public int size() {
return records.size();
}
public Stream<Map.Entry<String, List<Recipe>>> stream() {
return records.entrySet().stream();
}
public Stream<Triple<Recipe, String, Integer>> flatStream() {
return records.entrySet().stream().flatMap(i ->
IntStream.range(0, i.getValue().size()).mapToObj(j ->
new Triple<>(i.getValue().get(j), i.getKey(), j)));
}
public Stream<Triple<Recipe, String, Integer>> flatStream(String group) {
List<Recipe> l = records.get(group);
return IntStream.range(0, l.size()).mapToObj(j -> new Triple<>(l.get(j), group, j));
}
public void remove(String group, int index) {
List<Recipe> l = records.get(group);
l.remove(index);
if (l.isEmpty()) records.remove(group);
}
public Recipe getRecipe(String group, int index) {
return getGroup(group).get(index);
}
public List<Triple<Recipe, String, Integer>> getRecipes() {
return flatStream().collect(Collectors.toCollection(ArrayList::new));
}
public List<Triple<Recipe, String, Integer>> getRecipes(String group) {
return flatStream(group).collect(Collectors.toCollection(ArrayList::new));
}
public List<Triple<Recipe, String, Integer>> getRecipes(ILabel label, Recipe.enumIoType type) {
return getRecipes(flatStream(), r -> IntStream.range(0, type.getSize()).anyMatch(i ->
ILabel.MERGER.merge(label, r.getLabel(type)[i], true).isPresent()));
}
private List<Triple<Recipe, String, Integer>> getRecipes(Stream<Triple<Recipe, String, Integer>> list, Predicate<Recipe> pre) {
return list.filter(i -> pre.test(i.one)).collect(Collectors.toCollection(ArrayList::new));
}
public void forEach(BiConsumer<String, List<Recipe>> consumer) {
records.forEach(consumer);
}
public List<Recipe> getGroup(String group) {
return records.get(group);
}
public NBTTagList serialize() {
NBTTagList ret = new NBTTagList();
forEach((n, rs) -> {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString(KEY_NAME, n);
NBTTagList l = new NBTTagList();
rs.forEach(r -> l.appendTag(r.serialize()));
nbt.setTag(KEY_CONTENT, l);
ret.appendTag(nbt);
});
return ret;
}
}
@@ -1,185 +0,0 @@
package me.towdium.jecalculation.data.structure;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.polyfill.NBTHelper;
import me.towdium.jecalculation.utils.Utilities;
import me.towdium.jecalculation.utils.wrappers.Pair;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Author: towdium
* Date: 17-10-15.
*/
public class User {
public static final String KEY_RECIPE = "recipe";
public static final String KEY_RECENT = "recent";
public Recipes recipes;
public Recent recent; // client mode only
public User() {
recipes = new Recipes();
recent = new Recent();
}
public User(NBTTagCompound nbt) {
recipes = new Recipes(nbt.getTagList(KEY_RECIPE, 10));
recent = new Recent(nbt.getTagList(KEY_RECENT, 10));
}
public NBTTagCompound serialize() {
NBTTagCompound ret = new NBTTagCompound();
ret.setTag(KEY_RECIPE, recipes.serialize());
ret.setTag(KEY_RECENT, recent.serialize());
return ret;
}
public static class Recipes {
public static final String KEY_NAME = "name";
public static final String KEY_CONTENT = "content";
Utilities.OrderedHashMap<String, List<Recipe>> records = new Utilities.OrderedHashMap<>();
public Recipes() {
}
public Recipes(NBTTagList nbt) {
StreamSupport.stream(NBTHelper.spliterator(nbt), false).filter(g -> g instanceof NBTTagCompound)
.forEach(g -> {
NBTTagCompound group = (NBTTagCompound) g;
String name = group.getString(KEY_NAME);
NBTTagList recipes = group.getTagList(KEY_CONTENT, 10);
StreamSupport.stream(NBTHelper.spliterator(recipes), false)
.filter(r -> r instanceof NBTTagCompound).map(r -> (NBTTagCompound) r)
.forEach(r -> add(name, new Recipe(r)));
});
}
public void add(String group, Recipe recipe) {
records.get(group).orElseGet(() -> {
ArrayList<Recipe> ret = new ArrayList<>();
records.put(group, ret);
return ret;
}).add(recipe);
}
public void set(String group, int index, Recipe recipe) {
records.get(group).orElseGet(() -> {
throw new RuntimeException("Group not found: " + group + ".");
}).set(index, recipe);
}
public int size() {
return records.size();
}
public Stream<Pair<String, List<Recipe>>> stream() {
return records.stream();
}
public void remove(String group, int index) {
records.get(group).orElseGet(() -> {
throw new RuntimeException("Group not found: " + group + ".");
}).remove(index);
}
public List<Recipe> search(String group, ILabel label, Recipe.enumIoType type) {
return search(records.get(group).map(Collection::stream).orElseGet(Stream::empty),
r -> IntStream.range(0, type.getSize()).anyMatch(
i -> ILabel.MERGER.merge(label, r.getLabel(type)[i], true).isPresent()));
}
public List<Recipe> search(String group, String label, Recipe.enumIoType type) {
return search(records.get(group).map(Collection::stream).orElseGet(Stream::empty),
r -> IntStream.range(0, type.getSize()).anyMatch(
i -> Utilities.contains(r.getLabel(type)[i].getDisplayName(), label)));
}
public List<Recipe> search(ILabel label, Recipe.enumIoType type) {
return search(records.stream().flatMap(i -> i.two.stream()), r -> IntStream.range(0, type.getSize())
.anyMatch(i -> ILabel.MERGER
.merge(label, r.getLabel(
type)[i], true)
.isPresent()));
}
public List<Recipe> search(String label, Recipe.enumIoType type) {
return search(records.stream().flatMap(i -> i.two.stream()), r -> IntStream.range(0, type.getSize())
.anyMatch(i -> Utilities
.contains(r.getLabel(
type)[i].getDisplayName(),
label)));
}
private List<Recipe> search(Stream<Recipe> list, Predicate<Recipe> pre) {
return list.filter(pre).collect(Collectors.toCollection(ArrayList::new));
}
public void forEach(BiConsumer<String, List<Recipe>> consumer) {
records.forEach(consumer);
}
public Optional<List<Recipe>> get(String group) {
return records.get(group);
}
public NBTTagList serialize() {
NBTTagList ret = new NBTTagList();
forEach((n, rs) -> {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setString(KEY_NAME, n);
NBTTagList l = new NBTTagList();
rs.forEach(r -> l.appendTag(r.serialize()));
nbt.setTag(KEY_CONTENT, l);
ret.appendTag(nbt);
});
return ret;
}
}
public static class Recent {
Utilities.Recent<ILabel> record = new Utilities.Recent<>((a, b) -> a == ILabel.EMPTY || a.equals(b), 9);
public static final String IDENTIFIER = "recent";
public Recent(NBTTagList nbt) {
List<ILabel> ls = StreamSupport.stream(NBTHelper.spliterator(nbt), false)
.filter(n -> n instanceof NBTTagCompound)
.map(n -> ILabel.DESERIALIZER.deserialize((NBTTagCompound) n))
.collect(Collectors.toList());
new Utilities.ReversedIterator<>(ls).forEachRemaining(l -> record.push(l));
}
public Recent() {
}
public void push(ILabel label) {
record.push(label);
}
public ILabel getLatest() {
return record.toList().get(0);
}
public List<ILabel> getRecords() {
return record.toList();
}
public NBTTagList serialize() {
NBTTagList ret = new NBTTagList();
record.toList().forEach(l -> ret.appendTag(ILabel.DESERIALIZER.serialize(l)));
return ret;
}
}
}
@@ -1,7 +1,6 @@
package me.towdium.jecalculation.event;
import me.towdium.jecalculation.event.handlers.ControllerClient;
import me.towdium.jecalculation.event.handlers.ControllerServer;
import me.towdium.jecalculation.data.ControllerClient;
import me.towdium.jecalculation.event.handlers.InputEventHandler;
import java.util.ArrayList;
@@ -13,7 +12,5 @@ public class Handlers {
handlers = new ArrayList<>();
handlers.add(new InputEventHandler());
handlers.add(new ControllerClient());
handlers.add(new ControllerServer());
}
}
@@ -1,125 +0,0 @@
package me.towdium.jecalculation.event.handlers;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.network.FMLNetworkEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.JustEnoughCalculation;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.data.structure.Recipe;
import me.towdium.jecalculation.data.structure.User;
import me.towdium.jecalculation.network.packets.PCalculator;
import me.towdium.jecalculation.network.packets.PRecipe;
import me.towdium.jecalculation.utils.Utilities;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Author: towdium
* Date: 17-10-15.
*/
@SideOnly(Side.CLIENT)
public class ControllerClient {
static User recordWorld;
static User recordClient = new User();
static User getRecord() {
return recordWorld == null ? recordClient : recordWorld;
}
public static List<String> getGroups() {
User user = getRecord();
if (user.recipes.size() != 0) return user.recipes.stream().map(p -> p.one).collect(Collectors.toList());
else return Collections.singletonList(Utilities.I18n.format("common.default"));
}
public static void addRecipe(String group, Recipe recipe) {
getRecord().recipes.add(group, recipe);
JustEnoughCalculation.network.sendToServer(new PRecipe(group, -1, recipe));
}
public static void setRecipe(String group, int index, Recipe recipe) {
getRecord().recipes.set(group, index, recipe);
JustEnoughCalculation.network.sendToServer(new PRecipe(group, index, recipe));
}
public static void removeRecipe(String group, int index) {
getRecord().recipes.remove(group, index);
JustEnoughCalculation.network.sendToServer(new PRecipe(group, index, null));
}
/**
* This is used when syncing data from the server.
* Client record will be initialized when client starts.
*
* @param nbt {@link NBTTagCompound containing the user data}
*/
public static void init(@Nullable NBTTagCompound nbt) {
recordWorld = nbt == null ? new User() : new User(nbt);
}
@SubscribeEvent
public void onLogOut(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) {
recordWorld = null;
}
public static List<Recipe> search(String group, ILabel label, Recipe.enumIoType type) {
return getRecord().recipes.search(group, label, type);
}
public static List<Recipe> search(String group, String label, Recipe.enumIoType type) {
return getRecord().recipes.search(group, label, type);
}
public static List<Recipe> search(ILabel label, Recipe.enumIoType type) {
return getRecord().recipes.search(label, type);
}
public static List<Recipe> search(String label, Recipe.enumIoType type) {
return getRecord().recipes.search(label, type);
}
public static List<ILabel> getRecent() {
if (recordWorld == null) return recordClient.recent.getRecords();
else {
ArrayList<ILabel> ret = new ArrayList<>();
Optional<ItemStack> ois = Utilities.getStack();
ois.ifPresent(is -> {
User.Recent recent = new User.Recent(Utilities.getTag(is).getTagList(User.Recent.IDENTIFIER, 10));
ret.addAll(recent.getRecords());
});
return ret;
}
}
public static void setRecent(ILabel label) {
if (recordWorld == null) recordClient.recent.push(label);
else {
Optional<ItemStack> ois = Utilities.getStack();
ois.ifPresent(is -> {
User.Recent recent = new User.Recent(Utilities.getTag(is).getTagList(User.Recent.IDENTIFIER, 10));
recent.push(label);
Utilities.getTag(is).setTag(User.Recent.IDENTIFIER, recent.serialize());
JustEnoughCalculation.network.sendToServer(new PCalculator(is));
});
}
}
public static void syncFromServer(User u) {
recordWorld = u;
}
public static void loadFromLocal() {
recordClient = new User(); // TODO
}
public static void writeToLocal() {
// TODO
}
}
@@ -1,82 +0,0 @@
package me.towdium.jecalculation.event.handlers;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import me.towdium.jecalculation.JustEnoughCalculation;
import me.towdium.jecalculation.data.structure.Recipe;
import me.towdium.jecalculation.data.structure.User;
import me.towdium.jecalculation.network.packets.PRecord;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.event.entity.player.PlayerEvent.LoadFromFile;
import net.minecraftforge.event.entity.player.PlayerEvent.SaveToFile;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;
/**
* Author: towdium
* Date: 17-10-15.
*/
@ParametersAreNonnullByDefault
public class ControllerServer {
static HashMap<UUID, User> records = new HashMap<>();
/**
* @param uuid User UUID
* @param group Recipe group, crate when not exist
* @param index Recipe group, -1 for add
* @param recipe Recipe content, null for remove
*/
public static void modify(UUID uuid, String group, int index, @Nullable Recipe recipe) {
User.Recipes rs = records.get(uuid).recipes;
if (recipe == null) rs.remove(group, index);
else if (index == -1) rs.add(group, recipe);
else rs.set(group, index, recipe);
}
@SubscribeEvent
public void onJoin(PlayerEvent.PlayerLoggedInEvent e) {
JustEnoughCalculation.network.sendTo(new PRecord(records.get(e.player.getUniqueID())),
(EntityPlayerMP) e.player);
}
@SubscribeEvent
public void onQuit(PlayerEvent.PlayerLoggedOutEvent e) {
records.remove(e.player.getUniqueID());
}
@SubscribeEvent
public void onLoad(LoadFromFile e) {
try {
FileInputStream stream = new FileInputStream(e.getPlayerFile("jeca"));
NBTTagCompound tag = CompressedStreamTools.readCompressed(stream);
records.put(UUID.fromString(e.playerUUID), new User(tag));
} catch (FileNotFoundException ex) {
JustEnoughCalculation.logger.info("Record not found for "
+ e.entityPlayer.getDisplayName());
records.put(UUID.fromString(e.playerUUID), new User());
} catch (IOException | IllegalArgumentException ex) {
JustEnoughCalculation.logger.warn("Fail to load records for "
+ e.entityPlayer.getDisplayName());
}
}
@SubscribeEvent
public void onSave(SaveToFile e) {
try {
File file = e.getPlayerFile("jeca");
User user = records.get(UUID.fromString(e.playerUUID));
NBTTagCompound tag = user.serialize();
FileOutputStream fos = new FileOutputStream(file);
CompressedStreamTools.writeCompressed(tag, fos);
} catch (Exception ex) {
JustEnoughCalculation.logger.warn("Fail to save records for "
+ e.entityPlayer.getDisplayName());
}
}
}
@@ -3,32 +3,38 @@ package me.towdium.jecalculation.event.handlers;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.InputEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.JustEnoughCalculation;
import me.towdium.jecalculation.data.ControllerClient;
import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.gui.guis.GuiCalculator;
import me.towdium.jecalculation.network.ProxyClient;
import me.towdium.jecalculation.network.ClientHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.event.entity.EntityEvent;
/**
* Author: towdium
* Date: 8/13/17.
*/
@SuppressWarnings("unused")
public class InputEventHandler {
@SideOnly(Side.CLIENT)
@SubscribeEvent(receiveCanceled = true)
public void onKey(InputEvent.KeyInputEvent event) {
if (ProxyClient.keyOpenGui.isPressed()) {
if (ClientHandler.keyOpenGui.isPressed()) {
if (JustEnoughCalculation.side == JustEnoughCalculation.enumSide.CLIENT) JecaGui.displayGui(new GuiCalculator());
else Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentTranslation("chat.server_mode"));
}
}
@SideOnly(Side.CLIENT)
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onMouseClick(GuiScreenEvent.ActionPerformedEvent.Pre event) {
JustEnoughCalculation.logger.info("on gui screen event action performed event pre");
if (event.gui instanceof JecaGui) {
JustEnoughCalculation.logger.info("on mouse click in gui screen event");
JecaGui gui = (JecaGui) event.gui;
@@ -36,5 +42,11 @@ public class InputEventHandler {
}
}
@SubscribeEvent
public void onLogout(PlayerEvent.PlayerLoggedOutEvent event) {
JustEnoughCalculation.logger.info("on log out event");
ControllerClient.writeToLocal();;
}
}
@@ -33,6 +33,7 @@ public class Resource {
public static final Resource BTN_YES_F = new Resource(84, 0, 14, 14);
public static final Resource BTN_NO_N = new Resource(98, 14, 14, 14);
public static final Resource BTN_NO_F = new Resource(98, 0, 14, 14);
public static final Resource BTN_NO_D = new Resource(228, 0, 14, 14);
public static final Resource BTN_DISAMB_N = new Resource(112, 14, 14, 14);
public static final Resource BTN_DISAMB_F = new Resource(112, 0, 14, 14);
public static final Resource BTN_DISAMB_D = new Resource(242, 0, 14, 14);
@@ -11,6 +11,7 @@ import me.towdium.jecalculation.utils.Utilities;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
@@ -158,7 +159,7 @@ public class WLabel implements IWidget {
*/
EDITOR,
/**
* Slots to display calculate/search result. Rounded amount displayed.
* Slots to display calculate/getRecipes result. Rounded amount displayed.
*/
RESULT,
/**
@@ -43,6 +43,8 @@ public class WLabelScroll extends WContainer {
}
public void update(float f) {
if (f < 0) f = 0;
if (f > 1) f = 1;
int step = getStepAmount();
current = (int) (step * f);
if (current == step) current--;
@@ -52,7 +54,13 @@ public class WLabelScroll extends WContainer {
@Override
public boolean onScroll(JecaGui gui, int xMouse, int yMouse, int diff) {
boolean in = JecaGui.mouseIn(xPos, yPos, column * 18, row * 18, xMouse, yMouse);
if (in) scroll.setCurrent(getPos(current - diff));
if (in) {
scroll.setLsnrScroll(null);
float pos = getPos(current - diff);
scroll.setCurrent(pos);
update(pos);
scroll.setLsnrScroll(this::update);
}
return in;
}
@@ -74,8 +82,10 @@ public class WLabelScroll extends WContainer {
return filtered.size() != 0;
}
public void setLsnrUpdate(Consumer<Integer> lsnr) {
@SuppressWarnings("UnusedReturnValue")
public WLabelScroll setLsnrUpdate(Consumer<Integer> lsnr) {
lsnrUpdate = lsnr;
return this;
}
public ILabel getLabelAt(int index) {
@@ -7,6 +7,7 @@ import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.gui.Resource;
import org.lwjgl.input.Mouse;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.function.Consumer;
@@ -59,7 +60,7 @@ public class WScroll implements IWidget {
return JecaGui.mouseIn(xPos + 1, yPos + 1, 12, ySize - 2, xMouse, yMouse);
}
public WScroll setLsnrScroll(Consumer<Float> lsnrScroll) {
public WScroll setLsnrScroll(@Nullable Consumer<Float> lsnrScroll) {
this.lsnrScroll = lsnrScroll;
return this;
}
@@ -22,7 +22,7 @@ import java.util.stream.IntStream;
@SideOnly(Side.CLIENT)
public class WSwitcher extends WContainer {
public static final int SIZE = 13;
public Consumer<Integer> listener;
public Runnable listener;
protected int xPos, xSize, yPos;
protected WButton left, right;
protected WRectangle wRect;
@@ -57,7 +57,7 @@ public class WSwitcher extends WContainer {
});
wRect = new WRectangle(xPos + SIZE, yPos, xSize - 2 * SIZE, SIZE, JecaGui.COLOR_GUI_GREY);
wText = new WText(xPos + SIZE, yPos, xSize - 2 * SIZE, SIZE, JecaGui.Font.DEFAULT_SHADOW,
() -> temp == null ? keys.get(index.current()) : temp);
() -> temp == null ? (keys.isEmpty() ? "" : keys.get(index.current())) : temp);
index = new Circulator(keys.size());
refresh();
addAll(left, right, wRect, wText);
@@ -75,7 +75,7 @@ public class WSwitcher extends WContainer {
notifyLsnr();
}
public WSwitcher setListener(Consumer<Integer> listener) {
public WSwitcher setListener(Runnable listener) {
this.listener = listener;
return this;
}
@@ -90,18 +90,28 @@ public class WSwitcher extends WContainer {
return temp == null ? index.current() : -1;
}
public void setIndex(int i) {
if (temp != null) temp = null;
index.set(i);
refresh();
}
public List<String> getTexts() {
return keys;
}
public String getText() {
return temp == null ? keys.get(index.current()) : temp;
}
public void refresh() {
boolean b = temp == null && keys.size() < 2;
boolean b = keys.size() < (temp == null ? 2 : 1);
left.setDisabled(b);
right.setDisabled(b);
}
public void notifyLsnr() {
if (listener != null)
listener.accept(getIndex());
if (listener != null) listener.run();
}
}
@@ -6,7 +6,7 @@ import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.gui.Resource;
import me.towdium.jecalculation.gui.drawables.*;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.event.handlers.ControllerClient;
import me.towdium.jecalculation.data.ControllerClient;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
@@ -19,16 +19,18 @@ import java.util.List;
public class GuiDisambiguation extends IWPicker.Simple {
protected WLabelScroll lsUp;
protected WLabelScroll lsDown;
protected WSwitcher switcher;
protected List<List<ILabel>> record;
public GuiDisambiguation(List<List<ILabel>> record) {
this.record = record;
lsUp = new WLabelScroll(25, 48, 7, 3, WLabel.enumMode.PICKER, true);
lsDown = new WLabelScroll(25, 105, 7, 3, WLabel.enumMode.PICKER, true);
this.record = record;
switcher = new WSwitcher(7, 7, 162, this.record.size()).setListener(() -> setPage(switcher.getIndex()));
WTextField tf = new WTextField(25, 24, 90);
add(new WPanel());
add(new WSwitcher(7, 7, 162, this.record.size()).setListener(this::setPage));
add(switcher);
add(new WIcon(149, 24, 20, 20, Resource.ICN_HELP_N, Resource.ICN_HELP_F, "disambiguation.help"));
add(new WIcon(7, 48, 18, 54, Resource.ICN_LIST_N, Resource.ICN_LIST_F, "disambiguation.list"));
add(new WIcon(7, 105, 18, 54, Resource.ICN_LABEL_N, Resource.ICN_LABEL_F, "disambiguation.label"));
@@ -4,17 +4,16 @@ import codechicken.nei.recipe.IRecipeHandler;
import me.towdium.jecalculation.algorithm.CostList;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.data.structure.Recipe;
import me.towdium.jecalculation.event.handlers.ControllerClient;
import me.towdium.jecalculation.data.ControllerClient;
import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.gui.Resource;
import me.towdium.jecalculation.gui.drawables.*;
import me.towdium.jecalculation.utils.Utilities;
import me.towdium.jecalculation.utils.wrappers.Pair;
import me.towdium.jecalculation.utils.wrappers.Triple;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
@@ -25,26 +24,25 @@ import java.util.stream.Stream;
* Date: 17-9-8.
*/
public class GuiRecipe extends WContainer {
Pair<String, Integer> dest;
HashMap<Integer, List<ILabel>> disambiguation = new HashMap<>();
WSwitcher switcherGroup = new WSwitcher(7, 7, 162, ControllerClient.getGroups());
WButton buttonCopy = new WButtonIcon(83, 33, 20, 20, Resource.BTN_COPY_N, Resource.BTN_COPY_F, Resource.BTN_COPY_D,
"recipe.copy").setDisabled(true);
WTextField textField = new WTextField(49, 33, 119);
WButton buttonCopy = new WButtonIcon(83, 33, 20, 20, Resource.BTN_COPY_N, Resource.BTN_COPY_F,
Resource.BTN_COPY_D, "recipe.copy").setDisabled(true).setListenerLeft(() -> {
ControllerClient.addRecipe(switcherGroup.getText(), toRecipe());
JecaGui.displayParent();
});
WLabelGroup groupCatalyst = new WLabelGroup(28, 87, 7, 1, 20, 20, WLabel.enumMode.EDITOR);
WButton buttonDisamb = new WButtonIcon(102, 33, 20, 20, Resource.BTN_DISAMB_N, Resource.BTN_DISAMB_F,
Resource.BTN_DISAMB_D, "recipe.disamb").setDisabled(true)
.setListenerLeft(() -> {
if (disambiguation != null)
JecaGui.displayGui(
new GuiDisambiguation(
new ArrayList<>(
disambiguation
.values()))
.setCallback(
l -> {
JecaGui.displayParent();
JecaGui.getCurrent().hand = l;
}));
});
WButton buttonDisamb = new WButtonIcon(121, 33, 20, 20, Resource.BTN_DISAMB_N,
Resource.BTN_DISAMB_F, Resource.BTN_DISAMB_D, "recipe.disamb").setDisabled(true).setListenerLeft(() -> {
if (disambiguation != null) JecaGui.displayGui(new GuiDisambiguation(new ArrayList<>(disambiguation.values()))
.setCallback(l -> {
JecaGui.displayParent();
JecaGui.getCurrent().hand = l;
}));
});
WLabelGroup groupInput = new WLabelGroup(28, 111, 7, 2, 20, 20, WLabel.enumMode.EDITOR).setLsnrUpdate(i -> {
disambiguation.remove(i);
refresh();
@@ -62,12 +60,26 @@ public class GuiRecipe extends WContainer {
})));
WButton buttonSave = new WButtonIcon(26, 33, 20, 20, Resource.BTN_SAVE_N, Resource.BTN_SAVE_F, "recipe.save")
.setListenerLeft(() -> {
ControllerClient.addRecipe(switcherGroup.getText(), toRecipe());
if (dest == null)
ControllerClient.addRecipe(switcherGroup.getText(), toRecipe());
else {
if (textField.getText().equals(dest.one))
ControllerClient.setRecipe(dest.one, dest.two, toRecipe());
else {
ControllerClient.removeRecipe(dest.one, dest.two);
ControllerClient.addRecipe(switcherGroup.getText(), toRecipe());
}
}
JecaGui.displayParent();
});
WTextField textField = new WTextField(49, 33, 119);
WButton buttonNew = new WButtonIcon(7, 33, 20, 20, Resource.BTN_NEW_N, Resource.BTN_NEW_F, "recipe.new")
.setListenerLeft(() -> setModeNewGroup(true));
WButton buttonDel = new WButtonIcon(102, 33, 20, 20, Resource.BTN_NO_N, Resource.BTN_NO_F, Resource.BTN_NO_D,
"recipe.delete").setDisabled(true).setListenerLeft(() -> {
ControllerClient.removeRecipe(dest.one, dest.two);
JecaGui.displayParent();
});
WButton buttonYes = new WButtonIcon(7, 33, 20, 20, Resource.BTN_YES_N, Resource.BTN_YES_F, "recipe.confirm")
.setListenerLeft(() -> {
switcherGroup.setTemp(textField.getText());
@@ -77,6 +89,17 @@ public class GuiRecipe extends WContainer {
WButton buttonNo = new WButtonIcon(26, 33, 20, 20, Resource.BTN_NO_N, Resource.BTN_NO_F, "recipe.cancel")
.setListenerLeft(() -> setModeNewGroup(false));
public GuiRecipe(String group, int index) {
this();
dest = new Pair<>(group, index);
Recipe r = ControllerClient.getRecipe(group, index);
fromRecipe(r);
switcherGroup.setIndex(ControllerClient.getGroups().indexOf(group));
buttonCopy.setDisabled(false);
buttonDel.setDisabled(false);
}
public GuiRecipe() {
add(new WPanel());
add(new WIcon(7, 63, 21, 20, Resource.ICN_OUTPUT_N, Resource.ICN_OUTPUT_F, "recipe.output"));
@@ -84,15 +107,16 @@ public class GuiRecipe extends WContainer {
add(new WIcon(7, 111, 21, 40, Resource.ICN_INPUT_N, Resource.ICN_INPUT_F, "recipe.input"));
add(new WLine(57));
addAll(groupInput, groupCatalyst, groupOutput, switcherGroup);
if (switcherGroup.getTexts().isEmpty()) switcherGroup.setTemp(Utilities.I18n.format("common.default"));
setModeNewGroup(false);
}
public void setModeNewGroup(boolean b) {
if (b) {
removeAll(buttonNew, buttonLabel, buttonClear, buttonCopy, buttonSave, buttonDisamb);
removeAll(buttonNew, buttonLabel, buttonClear, buttonCopy, buttonSave, buttonDisamb, buttonDel);
addAll(buttonYes, buttonNo, textField);
} else {
addAll(buttonNew, buttonLabel, buttonClear, buttonCopy, buttonSave, buttonDisamb);
addAll(buttonNew, buttonLabel, buttonClear, buttonCopy, buttonSave, buttonDisamb, buttonDel);
removeAll(buttonYes, buttonNo, textField);
}
}
@@ -160,6 +184,16 @@ public class GuiRecipe extends WContainer {
return new Recipe(groupInput.getLabels(), groupCatalyst.getLabels(), groupOutput.getLabels());
}
void fromRecipe(Recipe r) {
groupInput.setLabel(Arrays.stream(r.getLabel(Recipe.enumIoType.INPUT))
.map(ILabel::copy).collect(Collectors.toList()), 0);
groupCatalyst.setLabel(Arrays.stream(r.getLabel(Recipe.enumIoType.CATALYST))
.map(ILabel::copy).collect(Collectors.toList()), 0);
groupOutput.setLabel(Arrays.stream(r.getLabel(Recipe.enumIoType.OUTPUT))
.map(ILabel::copy).collect(Collectors.toList()), 0);
}
void refresh() {
buttonDisamb.setDisabled(disambiguation.isEmpty());
}
@@ -1,22 +1,40 @@
package me.towdium.jecalculation.gui.guis;
import me.towdium.jecalculation.event.handlers.ControllerClient;
import me.towdium.jecalculation.data.structure.Recipe;
import me.towdium.jecalculation.data.ControllerClient;
import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.gui.Resource;
import me.towdium.jecalculation.gui.drawables.*;
import me.towdium.jecalculation.utils.Utilities;
import me.towdium.jecalculation.utils.wrappers.Triple;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class GuiSearch extends WContainer {
List<Triple<Recipe, String, Integer>> content;
WSwitcher switcherGroup;
WLabelScroll labelScroll;
public GuiSearch() {
add(new WPanel());
ArrayList<String> groups = new ArrayList<>();
groups.add(Utilities.I18n.format("gui.search.all"));
groups.addAll(ControllerClient.getGroups());
add(new WSwitcher(7, 7, 162, groups));
WTextField tf = new WTextField(25, 7, 90);
WLabelScroll ls = new WLabelScroll(7, 33, 8, 7, WLabel.enumMode.PICKER, true);
add(new WIcon(149, 7, 20, 20, Resource.ICN_HELP_N, Resource.ICN_HELP_F, "search.help"));
add(new WIcon(7, 7, 20, 20, Resource.ICN_TEXT_N, Resource.ICN_TEXT_F, "search.text"));
switcherGroup = new WSwitcher(7, 7, 162, groups).setListener(this::refresh);
labelScroll = new WLabelScroll(7, 51, 8, 6, WLabel.enumMode.PICKER, true);
add(new WPanel());
add(switcherGroup);
add(new WSearch(i -> content.stream().filter(j -> j.one.getRep() == i).findFirst().ifPresent(j ->
JecaGui.displayGui(false, true, new GuiRecipe(j.two, j.three))), new WTextField(25, 27, 90), labelScroll));
add(new WIcon(149, 27, 20, 20, Resource.ICN_HELP_N, Resource.ICN_HELP_F, "search.help"));
add(new WIcon(7, 27, 20, 20, Resource.ICN_TEXT_N, Resource.ICN_TEXT_F, "search.text"));
refresh();
}
public void refresh() {
int iGroup = switcherGroup.getIndex();
content = iGroup == 0 ? ControllerClient.getRecipes() : ControllerClient.getRecipes(switcherGroup.getText());
labelScroll.setLabels(content.stream().map(i -> i.one.getRep()).collect(Collectors.toCollection(ArrayList::new)));
}
}
@@ -40,7 +40,7 @@ public class PickerSimple extends IWPicker.Simple {
public static class FluidStack extends PickerSimple {
public FluidStack() {
super(FluidRegistry.getRegisteredFluids().entrySet().stream()
.map(e -> new LFluidStack(e.getValue(), 1000)).collect(Collectors.toList()),
.map(e -> new LFluidStack(1000, e.getValue())).collect(Collectors.toList()),
"picker_fluid_stack");
}
}
@@ -1,102 +0,0 @@
package me.towdium.jecalculation.item;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.JustEnoughCalculation;
import me.towdium.jecalculation.polyfill.mc.util.NonNullList;
import me.towdium.jecalculation.utils.IllegalPositionException;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon;
import net.minecraft.world.World;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.List;
/**
* Author: towdium
* Date: 8/10/17.
*/
@ParametersAreNonnullByDefault
public class ItemCalculator extends Item {
public static ItemCalculator INSTANCE = new ItemCalculator();
public static final String CRAFTING_NAME = "item_calculator_crafting";
public static final String MATH_NAME = "item_calculator_math";
private IIcon mathIcon;
private ItemCalculator() {
setHasSubtypes(true);
setMaxStackSize(1);
setCreativeTab(CreativeTabs.tabTools);
setUnlocalizedName("item_calculator");
setMaxDamage(1);
}
public static void registerItems() {
GameRegistry.registerItem(INSTANCE, INSTANCE.getUnlocalizedName());
}
@Override
public void getSubItems(Item item, CreativeTabs tab, List items) {
if (tab == CreativeTabs.tabAllSearch || tab == CreativeTabs.tabTools) {
items.add(new ItemStack(this, 1, 0));
items.add(new ItemStack(this, 1, 1));
}
}
@Override
public IIcon getIconFromDamage(int meta) {
return meta == 1 ? this.mathIcon : this.itemIcon;
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister) {
this.itemIcon = iconRegister.registerIcon(JustEnoughCalculation.Reference.MODID + ":" + CRAFTING_NAME);
this.mathIcon = iconRegister.registerIcon(JustEnoughCalculation.Reference.MODID + ":" + MATH_NAME);
}
@SideOnly(Side.CLIENT)
static void setModelLocation(Item item, int meta, String id) {
item.setTextureName(JustEnoughCalculation.Reference.MODID + ":" + id);
}
@SideOnly(Side.CLIENT)
static void setModelLocation(Item item) {
if (item.getHasSubtypes()) {
NonNullList<ItemStack> stacks = NonNullList.create();
item.getSubItems(item, CreativeTabs.tabAllSearch, stacks);
for (ItemStack s : stacks) {
setModelLocation(item, s.getItemDamage(), item.getUnlocalizedName(s).substring(5));
}
} else {
setModelLocation(item, 0, item.getUnlocalizedName().substring(5));
}
}
@Override
public String getUnlocalizedName(ItemStack stack) {
switch (stack.getItemDamage()) {
case 0:
return "item.item_calculator_crafting";
case 1:
return "item.item_calculator_math";
default:
throw new IllegalPositionException(String.format("item damage %d", stack.getItemDamage()));
}
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World worldIn, EntityPlayer playerIn) {
if (JustEnoughCalculation.side != JustEnoughCalculation.enumSide.CLIENT)
JustEnoughCalculation.proxy.displayCalculator();
return super.onItemRightClick(itemStack, worldIn, playerIn);
}
}
@@ -1,40 +1,41 @@
package me.towdium.jecalculation.network;
import cpw.mods.fml.client.registry.ClientRegistry;
import cpw.mods.fml.common.FMLCommonHandler;
import me.towdium.jecalculation.data.ControllerClient;
import me.towdium.jecalculation.event.Handlers;
import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.gui.guis.GuiCalculator;
import me.towdium.jecalculation.command.JecaCommand;
import me.towdium.jecalculation.data.label.ILabel;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.input.Keyboard;
public class ProxyClient extends ProxyServer {
public class ClientHandler {
public static final KeyBinding keyOpenGui =
new KeyBinding("key.open_gui", Keyboard.KEY_NONE, "key.category");
@Override
public void initPre() {
super.initPre();
Handlers.handlers.forEach(FMLCommonHandler.instance().bus()::register);
}
@Override
public void initPost() {
super.initPost();
ILabel.initServer();
ClientCommandHandler.instance.registerCommand(new JecaCommand());
ILabel.initClient();
ControllerClient.loadFromLocal();
}
@Override
public void init() {
super.init();
ClientRegistry.registerKeyBinding(keyOpenGui);
}
@Override
public void displayCalculator() {
super.displayCalculator();
JecaGui.displayGui(new GuiCalculator());
public EntityPlayer getPlayer() {
return Minecraft.getMinecraft().thePlayer;
}
}
@@ -1,20 +0,0 @@
package me.towdium.jecalculation.network;
/**
* Author: towdium
* Date: 17-10-10.
*/
public interface IProxy {
default void initPre() {
}
default void init() {
}
default void initPost() {
}
default void displayCalculator() {
}
}
@@ -1,23 +0,0 @@
package me.towdium.jecalculation.network;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import me.towdium.jecalculation.gui.JecaGui;
import me.towdium.jecalculation.data.label.ILabel;
import me.towdium.jecalculation.event.Handlers;
import me.towdium.jecalculation.item.ItemCalculator;
import net.minecraftforge.common.MinecraftForge;
public class ProxyServer implements IProxy {
@Override
public void initPre() {
GameRegistry.registerItem(ItemCalculator.INSTANCE, ItemCalculator.INSTANCE.getUnlocalizedName());
Handlers.handlers.forEach(FMLCommonHandler.instance().bus()::register);
MinecraftForge.EVENT_BUS.register(JecaGui.class);
}
@Override
public void initPost() {
ILabel.initServer();
}
}
@@ -1,42 +0,0 @@
package me.towdium.jecalculation.network.packets;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf;
import me.towdium.jecalculation.item.ItemCalculator;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
public class PCalculator implements IMessage, IMessageHandler<PCalculator, IMessage> {
ItemStack stack;
public PCalculator() {
}
public PCalculator(ItemStack stack) {
this.stack = stack;
}
@Override
public void fromBytes(ByteBuf buf) {
stack = ByteBufUtils.readItemStack(buf);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeItemStack(buf, stack);
}
@Override
public IMessage onMessage(PCalculator message, MessageContext ctx) {
InventoryPlayer inventory = ctx.getServerHandler().playerEntity.inventory;
ItemStack calculator = inventory.getCurrentItem();
if (calculator != null && calculator.getItem() instanceof ItemCalculator) {
inventory.setInventorySlotContents(inventory.currentItem, message.stack);
return null;
}
return null;
}
}
@@ -1,56 +0,0 @@
package me.towdium.jecalculation.network.packets;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf;
import me.towdium.jecalculation.data.structure.Recipe;
import me.towdium.jecalculation.event.handlers.ControllerServer;
import net.minecraft.nbt.NBTTagCompound;
import java.util.UUID;
public class PRecipe implements IMessage, IMessageHandler<PRecipe, IMessage> {
static final String KEY_GROUP = "group";
static final String KEY_INDEX = "index";
static final String KEY_RECIPE = "recipe";
String group;
int index;
Recipe recipe;
public PRecipe() {
}
public PRecipe(String group, int index, Recipe recipe) {
this.group = group;
this.index = index;
this.recipe = recipe;
}
@Override
public void fromBytes(ByteBuf buf) {
NBTTagCompound tag = ByteBufUtils.readTag(buf);
tag = tag == null ? new NBTTagCompound() : tag;
group = tag.getString(KEY_GROUP);
index = tag.getInteger(KEY_INDEX);
recipe = tag.hasKey(KEY_RECIPE) ? new Recipe(tag.getCompoundTag(KEY_RECIPE)) : null;
}
@Override
public void toBytes(ByteBuf buf) {
NBTTagCompound tag = new NBTTagCompound();
tag.setString(KEY_GROUP, group);
tag.setInteger(KEY_INDEX, index);
if (recipe != null) tag.setTag(KEY_RECIPE, recipe.serialize());
ByteBufUtils.writeTag(buf, tag);
}
@Override
public IMessage onMessage(PRecipe message, MessageContext ctx) {
UUID uuid = ctx.getServerHandler().playerEntity.getUniqueID();
ControllerServer.modify(uuid, message.group, message.index, message.recipe);
return null;
}
}
@@ -1,38 +0,0 @@
package me.towdium.jecalculation.network.packets;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf;
import me.towdium.jecalculation.data.structure.User;
import me.towdium.jecalculation.event.handlers.ControllerClient;
import net.minecraft.nbt.NBTTagCompound;
public class PRecord implements IMessage, IMessageHandler<PRecord, IMessage> {
User user;
public PRecord(User user) {
this.user = user;
}
public PRecord() {
}
@Override
public void fromBytes(ByteBuf buf) {
NBTTagCompound tag = ByteBufUtils.readTag(buf);
user = new User(tag == null ? new NBTTagCompound() : tag);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeTag(buf, user.serialize());
}
@Override
public IMessage onMessage(PRecord message, MessageContext ctx) {
ControllerClient.syncFromServer(message.user);
return null;
}
}
@@ -1,30 +1,24 @@
package me.towdium.jecalculation.utils;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import cpw.mods.fml.common.registry.GameData;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import me.towdium.jecalculation.JustEnoughCalculation;
import me.towdium.jecalculation.item.ItemCalculator;
import me.towdium.jecalculation.polyfill.NBTHelper;
import me.towdium.jecalculation.utils.wrappers.Pair;
import me.towdium.jecalculation.utils.wrappers.Wrapper;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.Fluid;
import org.apache.commons.lang3.StringEscapeUtils;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
@@ -36,17 +30,6 @@ import java.util.stream.StreamSupport;
@ParametersAreNonnullByDefault
public class Utilities {
final static int[] scaleTable = {9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE};
static Map<String, String> dictionary = new HashMap<>();
public static Collector toArrayList = Collectors.toCollection(ArrayList::new);
static {
Map<String, ModContainer> modMap = Loader.instance().getIndexedModList();
for (Map.Entry<String, ModContainer> modEntry : modMap.entrySet()) {
String lowercaseId = modEntry.getKey().toLowerCase(Locale.ENGLISH);
String modName = modEntry.getValue().getName();
dictionary.put(lowercaseId, modName);
}
}
public static boolean stackEqual(ItemStack a, ItemStack b) {
return a.getItem() == b.getItem() && a.getItemDamage() == b.getItemDamage() &&
@@ -84,21 +67,19 @@ public class Utilities {
// MOD NAME
@Nullable
public static String getModName(ItemStack stack) {
String name = GameData.getItemRegistry().getNameForObject(stack.getItem());
name = name.substring(0, name.indexOf(":"));
if (name.equals("minecraft"))
return "Minecraft";
else
return dictionary.get(name);
public static String getModName(Item item) {
String name = GameData.getItemRegistry().getNameForObject(item);
String id = name.substring(0, name.indexOf(":"));
return id.equals("minecraft") ? "Minecraft" : Loader.instance().getIndexedModList().get(id).getName();
}
public static String getModName(FluidStack stack) {
String name = stack.getFluid().getName();
public static String getModName(Fluid fluid) {
String name = fluid.getName();
if (name.equals("lava") || name.equals("water"))
return "Minecraft";
else
return dictionary.get(stack.getFluid().getStillIcon().getIconName().split(":")[0]);
return Loader.instance().getIndexedModList().get(fluid.getStillIcon().getIconName().split(":")[0])
.getName();
}
public static NBTTagCompound getTag(ItemStack is) {
@@ -109,13 +90,26 @@ public class Utilities {
return s1.contains(s2);
}
// get calculator item in player inventory
public static Optional<ItemStack> getStack() {
InventoryPlayer inv = Minecraft.getMinecraft().thePlayer.inventory;
ItemStack is = inv.getCurrentItem();
if (is.getItem() instanceof ItemCalculator) return Optional.of(is);
return Optional.empty();
}
// public static Recipes getRecipes(EntityPlayer player) {
// IExtendedEntityProperties properties = player
// .getExtendedProperties(JecaCapabilityProvider.PROPERTIES_NAME);
// if(properties instanceof JecaCapabilityProvider) {
// return ((JecaCapabilityProvider) properties).record;
// } else {
// JustEnoughCalculation.logger.info("getExtendedProperties error: " + properties.toString());
// return new Recipes();
// }
// }
// // get calculator item in player inventory
// public static Optional<ItemStack> getStack() {
// InventoryPlayer inv = Minecraft.getMinecraft().thePlayer.inventory;
// ItemStack is = inv.getCurrentItem();
// if (is.getItem() instanceof ItemCalculator)
// return Optional.of(is);
// return Optional.empty();
// }
public static void setStack(ItemStack is) {
@@ -239,6 +233,7 @@ public class Utilities {
public static class I18n {
public static Pair<String, Boolean> search(String translateKey, Object... parameters) {
Pair<String, Boolean> ret = new Pair<>(null, null);
translateKey = "jecharacters." + translateKey;
String buffer = net.minecraft.client.resources.I18n.format(translateKey, parameters);
ret.two = !buffer.equals(translateKey);
buffer = StringEscapeUtils.unescapeJava(buffer);
@@ -277,49 +272,4 @@ public class Utilities {
return (List<T>) data.clone();
}
}
public static class OrderedHashMap<K, V> {
public HashMap<K, Integer> index = new HashMap<>();
public List<Pair<K, V>> value = new ArrayList<>();
public void put(K key, V value) {
if (index.containsKey(key)) this.value.set(index.get(key), new Pair<>(key, value));
else {
index.put(key, this.value.size());
this.value.add(new Pair<>(key, value));
}
}
public Optional<V> get(int index) {
Pair<K, V> p = value.get(index);
return Optional.ofNullable(p == null ? null : p.two);
}
public Optional<V> get(K key) {
Integer i = index.get(key);
return Optional.ofNullable(i == null ? null : value.get(i).two);
}
public int getIndex(K key) {
Integer ret = index.get(key);
return ret == null ? -1 : ret;
}
public Optional<K> getKey(int index) {
Pair<K, V> ret = value.get(index);
return Optional.ofNullable(ret == null ? null : ret.one);
}
public void forEach(BiConsumer<K, V> func) {
value.forEach(p -> func.accept(p.one, p.two));
}
public Stream<Pair<K, V>> stream() {
return value.stream();
}
public int size() {
return value.size();
}
}
}