Fix the rest of the "easy" compile errors (#5151)

* Add Entity.changeDimension patch and transitively required patches

* Fix throws declaration on CommandSetDimension#execute

* Fix rest of errors in fluid package

* Add PLAYER_REACH attribute

* Fix compile errors in fml.client.config and add GuiButton patch

* Delete unnecessary client.config classes, fix all config errors

* Comment some fluid errors in models

* Fix all errors in common package root, except ForgeHooks

* Mass comment network package

* Experimental conversion of extended states to generic base class

* Fix errors in common.util

* Remove config annotation stuff cuz lex said so

* Make extended state stuff compile fully
This commit is contained in:
tterrag authored and GitHub committed 2018-09-18 00:04:02 -04:00
1 parent 6814cbf0df
commit c4cf950863
72 files changed
+610 -5996

No files matched your search

@@ -411,7 +411,7 @@ public class DimensionManager
finally
{
MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(w));
w.flush();
w.close();
setWorld(id, null, w.getMinecraftServer());
}
}
@@ -56,6 +56,7 @@ import net.minecraftforge.common.config.Property;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.server.ServerLifecycleHooks;
import net.minecraftforge.fml.ModContainer;
import net.minecraftforge.fml.ModList;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
@@ -505,7 +506,7 @@ public class ForgeChunkManager
String modId = ticketHolder.getString("Owner");
boolean isPlayer = ForgeVersion.MOD_ID.equals(modId);
if (!isPlayer && !Loader.isModLoaded(modId))
if (!isPlayer && !ModList.get().isLoaded(modId))
{
LOGGER.warn(CHUNK_MANAGER, "Found chunkloading data for mod {} which is currently not available or active - it will be removed from the world save", modId);
continue;
@@ -678,7 +679,7 @@ public class ForgeChunkManager
private static ModContainer getContainer(Object mod)
{
ModContainer container = Loader.instance().getModObjectList().inverse().get(mod);
ModContainer container = ModList.get().getModContainerByObject(mod).orElse(null);
return container;
}
@@ -1036,7 +1037,7 @@ public class ForgeChunkManager
NBTTagList tileEntities = nbt.getTagList("TileEntities", Constants.NBT.TAG_COMPOUND);
for (int i = 0; i < tileEntities.size(); ++i)
{
TileEntity tileEntity = TileEntity.create(world, tileEntities.getCompoundTagAt(i));
TileEntity tileEntity = TileEntity.func_203403_c(tileEntities.getCompoundTagAt(i));
if (tileEntity != null) chunk.addTileEntity(tileEntity);
}
}
@@ -77,6 +77,7 @@ import net.minecraft.item.ItemMonsterPlacer;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemPotion;
import net.minecraft.item.ItemSpade;
import net.minecraft.item.ItemSpawnEgg;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTippedArrow;
import net.minecraft.item.ItemUseContext;
@@ -120,6 +121,7 @@ import net.minecraft.world.storage.loot.LootEntry;
import net.minecraft.world.storage.loot.LootTable;
import net.minecraft.world.storage.loot.LootTableManager;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.event.DifficultyChangeEvent;
@@ -1283,21 +1285,6 @@ public class ForgeHooks
MinecraftForge.EVENT_BUS.post(new BlockEvent.CropGrowEvent.Post(worldIn, pos, state, worldIn.getBlockState(pos)));
}
private static final ClassValue<String> registryNames = new ClassValue<String>()
{
@Override
@SuppressWarnings("unchecked")
protected String computeValue(Class<?> type)
{
return String.valueOf(TileEntity.getKey((Class<? extends TileEntity>) type));
}
};
public static String getRegistryName(Class<? extends TileEntity> type)
{
return registryNames.get(type);
}
public static boolean loadAdvancements(Map<ResourceLocation, Advancement.Builder> map)
{
boolean errored = false;
@@ -1370,7 +1357,7 @@ public class ForgeHooks
true, true
);
}
/* TODO this should be unnecessary now?
public static void sendRecipeBook(NetHandlerPlayServer connection, State state, List<IRecipe> recipes, List<IRecipe> display, boolean isGuiOpen, boolean isFilteringCraftable)
{
NetworkDispatcher disp = NetworkDispatcher.get(connection.getNetworkManager());
@@ -1386,7 +1373,7 @@ public class ForgeHooks
if (!recipes.isEmpty() || !display.isEmpty())
connection.sendPacket(new SPacketRecipeBook(state, recipes, display, isGuiOpen, isFilteringCraftable));
}
*/
public static void onAdvancement(EntityPlayerMP player, Advancement advancement)
{
MinecraftForge.EVENT_BUS.post(new AdvancementEvent(player, advancement));
@@ -1406,7 +1393,7 @@ public class ForgeHooks
if (item instanceof ItemEnchantedBook)
{
NBTTagList enchantmentsNbt = ItemEnchantedBook.getEnchantments(itemStack);
if (enchantmentsNbt.tagCount() == 1)
if (enchantmentsNbt.size() == 1)
{
NBTTagCompound nbttagcompound = enchantmentsNbt.getCompoundTagAt(0);
Enchantment enchantment = Enchantment.getEnchantmentByID(nbttagcompound.getShort("id"));
@@ -1429,9 +1416,9 @@ public class ForgeHooks
return resourceLocation.getNamespace();
}
}
else if (item instanceof ItemMonsterPlacer)
else if (item instanceof ItemSpawnEgg)
{
ResourceLocation resourceLocation = ItemMonsterPlacer.getNamedIdFrom(itemStack);
ResourceLocation resourceLocation = ((ItemSpawnEgg)item).func_208076_b(null).getRegistryName();
if (resourceLocation != null)
{
return resourceLocation.getNamespace();
@@ -428,7 +428,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
NBTTagCompound forgeData = new NBTTagCompound();
NBTTagCompound dimData = DimensionManager.saveDimensionDataMap();
forgeData.setTag("DimensionData", dimData);
FluidRegistry.writeDefaultFluidList(forgeData);
// TODO fluids FluidRegistry.writeDefaultFluidList(forgeData);
return forgeData;
}
@@ -436,7 +436,7 @@ public class ForgeMod implements WorldPersistenceHooks.WorldPersistenceHook
public void readData(SaveHandler handler, WorldInfo info, NBTTagCompound tag)
{
DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompoundTag("DimensionData") : null);
FluidRegistry.loadFluidDefaults(tag);
// TODO fluids FluidRegistry.loadFluidDefaults(tag);
}
public void mappingChanged(FMLModIdMappingEvent evt)
@@ -169,8 +169,8 @@ public interface ISpecialArmor
{
ItemArmor armor = (ItemArmor)stack.getItem();
prop = new ArmorProperties(0, 0, Integer.MAX_VALUE);
prop.Armor = armor.damageReduceAmount;
prop.Toughness = armor.toughness;
prop.Armor = armor.func_200881_e();
prop.Toughness = armor.getToughness();
}
if (prop != null)
{
@@ -85,7 +85,7 @@ public class MinecraftForge
UsernameCache.load();
// Load before all the mods, so MC owns the MC fluids
FluidRegistry.validateFluidRegistry();
// TODO Fluids FluidRegistry.validateFluidRegistry();
ForgeHooks.initTools();
//For all the normal CrashReport classes to be defined. We're in MC's classloader so this should all be fine
@@ -34,6 +34,7 @@ import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.gen.feature.template.TemplateManager;
import net.minecraft.world.storage.IPlayerFileData;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraft.world.storage.SessionLockException;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.storage.WorldInfo;
import net.minecraft.world.WorldServer;
@@ -55,7 +56,7 @@ public class WorldSpecificSaveHandler implements ISaveHandler
}
@Override public WorldInfo loadWorldInfo() { return parent.loadWorldInfo(); }
@Override public void checkSessionLock() throws MinecraftException { parent.checkSessionLock(); }
@Override public void checkSessionLock() throws SessionLockException { parent.checkSessionLock(); }
@Override public IChunkLoader getChunkLoader(Dimension var1) { return parent.getChunkLoader(var1); }
@Override public void saveWorldInfoWithPlayer(WorldInfo var1, NBTTagCompound var2) { parent.saveWorldInfoWithPlayer(var1, var2); }
@Override public void saveWorldInfo(WorldInfo var1){ parent.saveWorldInfo(var1); }
@@ -37,7 +37,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
import net.minecraftforge.fml.client.config.IConfigEntry;
public class ConfigCategory implements Map<String, Property>
{
@@ -30,8 +30,8 @@ import com.google.common.collect.Lists;
import net.minecraftforge.fml.client.config.ConfigGuiType;
import net.minecraftforge.fml.client.config.DummyConfigElement.DummyCategoryElement;
import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
import net.minecraftforge.fml.client.config.GuiEditArrayEntries.IArrayEntry;
import net.minecraftforge.fml.client.config.IConfigEntry;
import net.minecraftforge.fml.client.config.IArrayEntry;
import net.minecraftforge.fml.client.config.IConfigElement;
/**
@@ -360,59 +360,4 @@ public class ConfigElement implements IConfigElement
{
return isProperty ? prop.getMaxValue() : null;
}
/**
* Provides a ConfigElement derived from the annotation-based config system
* @param configClass the class which contains the configuration
* @return A ConfigElement based on the described category.
*/
public static IConfigElement from(Class<?> configClass)
{
Config annotation = configClass.getAnnotation(Config.class);
if (annotation == null)
throw new RuntimeException(String.format("The class '%s' has no @Config annotation!", configClass.getName()));
Configuration config = ConfigManager.getConfiguration(annotation.modid(), annotation.name());
if (config == null)
{
String error = String.format("The configuration '%s' of mod '%s' isn't loaded with the ConfigManager!", annotation.name(), annotation.modid());
throw new RuntimeException(error);
}
String name = Strings.isNullOrEmpty(annotation.name()) ? annotation.modid() : annotation.name();
String langKey = name;
Config.LangKey langKeyAnnotation = configClass.getAnnotation(Config.LangKey.class);
if (langKeyAnnotation != null)
{
langKey = langKeyAnnotation.value();
}
if (annotation.category().isEmpty())
{
List<IConfigElement> elements = Lists.newArrayList();
Set<String> catNames = config.getCategoryNames();
for (String catName : catNames)
{
if (catName.isEmpty())
continue;
ConfigCategory category = config.getCategory(catName);
if (category.isChild())
continue;
DummyCategoryElement element = new DummyCategoryElement(category.getName(), category.getLanguagekey(), new ConfigElement(category).getChildElements());
element.setRequiresMcRestart(category.requiresMcRestart());
element.setRequiresWorldRestart(category.requiresWorldRestart());
elements.add(element);
}
return new DummyCategoryElement(name, langKey, elements);
}
else
{
ConfigCategory category = config.getCategory(annotation.category());
DummyCategoryElement element = new DummyCategoryElement(name, langKey, new ConfigElement(category).getChildElements());
element.setRequiresMcRestart(category.requiresMcRestart());
element.setRequiresWorldRestart(category.requiresWorldRestart());
return element;
}
}
}
@@ -1,383 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.config;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import net.minecraftforge.common.config.Config.Comment;
import net.minecraftforge.common.config.Config.LangKey;
import net.minecraftforge.common.config.Config.Name;
import net.minecraftforge.fml.common.FMLPaths;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.LoaderException;
import net.minecraftforge.fml.loading.moddiscovery.ModAnnotation.EnumHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ConfigManager
{
private static final Logger LOGGER = LogManager.getLogger();
private static Map<String, Multimap<Config.Type, ASMData>> asm_data = Maps.newHashMap();
static Map<Class<?>, ITypeAdapter> ADAPTERS = Maps.newHashMap();
static Map<Class<?>, Class<?>> ARRAY_REMAP = Maps.newHashMap();
private static Map<String, Configuration> CONFIGS = Maps.newHashMap();
private static Map<String, Set<Class<?>>> MOD_CONFIG_CLASSES = Maps.newHashMap();
static
{
register(boolean.class, TypeAdapters.bool);
register(boolean[].class, TypeAdapters.boolA);
register(Boolean.class, TypeAdapters.Bool);
register(Boolean[].class, TypeAdapters.BoolA);
register(float.class, TypeAdapters.flt);
register(float[].class, TypeAdapters.fltA);
register(Float.class, TypeAdapters.Flt);
register(Float[].class, TypeAdapters.FltA);
register(double.class, TypeAdapters.dbl);
register(double[].class, TypeAdapters.dblA);
register(Double.class, TypeAdapters.Dbl);
register(Double[].class, TypeAdapters.DblA);
register(byte.class, TypeAdapters.byt);
register(byte[].class, TypeAdapters.bytA);
register(Byte.class, TypeAdapters.Byt);
register(Byte[].class, TypeAdapters.BytA);
register(char.class, TypeAdapters.chr);
register(char[].class, TypeAdapters.chrA);
register(Character.class, TypeAdapters.Chr);
register(Character[].class, TypeAdapters.ChrA);
register(short.class, TypeAdapters.shrt);
register(short[].class, TypeAdapters.shrtA);
register(Short.class, TypeAdapters.Shrt);
register(Short[].class, TypeAdapters.ShrtA);
register(int.class, TypeAdapters.int_);
register(int[].class, TypeAdapters.intA);
register(Integer.class, TypeAdapters.Int);
register(Integer[].class, TypeAdapters.IntA);
register(String.class, TypeAdapters.Str);
register(String[].class, TypeAdapters.StrA);
ARRAY_REMAP.put(Boolean.class, Boolean[].class );
ARRAY_REMAP.put(Float.class, Float[].class );
ARRAY_REMAP.put(Double.class, Double[].class );
ARRAY_REMAP.put(Byte.class, Byte[].class );
ARRAY_REMAP.put(Character.class, Character[].class);
ARRAY_REMAP.put(Short.class, Short[].class );
ARRAY_REMAP.put(Integer.class, Integer[].class );
ARRAY_REMAP.put(String.class, String[].class );
}
private static void register(Class<?> cls, ITypeAdapter adpt)
{
ADAPTERS.put(cls, adpt);
}
public static void loadData(ASMDataTable data)
{
LOGGER.debug("Loading @Config anotation data");
for (ASMData target : data.getAll(Config.class.getName()))
{
String modid = (String)target.getAnnotationInfo().get("modid");
Multimap<Config.Type, ASMData> map = asm_data.computeIfAbsent(modid, k -> ArrayListMultimap.create());
EnumHolder tholder = (EnumHolder)target.getAnnotationInfo().get("type");
Config.Type type = tholder == null ? Config.Type.INSTANCE : Config.Type.valueOf(tholder.getValue());
map.put(type, target);
}
}
/**
* Bounces to sync().
* TODO: remove
*/
public static void load(String modid, Config.Type type)
{
sync(modid, type);
}
/**
* Synchronizes configuration data between the file on disk, the {@code Configuration} object and the annotated
* mod classes containing the configuration variables.
*
* When first called, this method will try to load the configuration from disk. If this fails, because the file
* does not exist, it will be created with default values derived from the mods config classes variable default values
* and comments and ranges, as well as configuration names based on the appropriate annotations found in {@code @Config}.
*
* Note, that this method is being called by the {@link FMLModContaier}, so the mod needn't call it in init().
*
* If this method is called after the initial load, it will check whether the values in the Configuration object differ
* from the values in the corresponding variables. If they differ, it will either overwrite the variables if the Configuration
* object is marked as changed (e.g. if it was changed with the ConfigGui) or otherwise overwrite the Configuration object's values.
* It then proceeds to saving the changes to disk.
* @param modid the mod's ID for which the configuration shall be loaded
* @param type the configuration type, currently always {@code Config.Type.INSTANCE}
*/
public static void sync(String modid, Config.Type type)
{
LOGGER.debug("Attempting to inject @Config classes into {} for type {}", modid, type);
ClassLoader mcl = Loader.instance().getModClassLoader();
File configDir = FMLPaths.FMLCONFIG.get().toFile();
Multimap<Config.Type, ASMData> map = asm_data.get(modid);
if (map == null)
return;
for (ASMData targ : map.get(type))
{
try
{
Class<?> cls = Class.forName(targ.getClassName(), true, mcl);
Set<Class<?>> modConfigClasses = MOD_CONFIG_CLASSES.computeIfAbsent(modid, k -> Sets.<Class<?>>newHashSet());
modConfigClasses.add(cls);
String name = (String)targ.getAnnotationInfo().get("name");
if (name == null)
name = modid;
String category = (String)targ.getAnnotationInfo().get("category");
if (category == null)
category = "general";
File file = new File(configDir, name + ".cfg");
boolean loading = false;
Configuration cfg = CONFIGS.get(file.getAbsolutePath());
if (cfg == null)
{
cfg = new Configuration(file);
cfg.load();
CONFIGS.put(file.getAbsolutePath(), cfg);
loading = true;
}
sync(cfg, cls, modid, category, loading, null);
cfg.save();
}
catch (Exception e)
{
LOGGER.error("An error occurred trying to load a config for {} into {}", targ.getClassName(), e);
throw new LoaderException(e);
}
}
}
public static Class<?>[] getModConfigClasses(String modid)
{
return (MOD_CONFIG_CLASSES.containsKey(modid) ? MOD_CONFIG_CLASSES.get(modid).toArray(new Class<?>[0]) : new Class<?>[0]);
}
public static boolean hasConfigForMod(String modid)
{
return asm_data.containsKey(modid);
}
// =======================================================
// INTERNAL
// =======================================================
static Configuration getConfiguration(String modid, String name) {
if (Strings.isNullOrEmpty(name))
name = modid;
File configDir = FMLPaths.FMLCONFIG.get().toFile();
File configFile = new File(configDir, name + ".cfg");
return CONFIGS.get(configFile.getAbsolutePath());
}
private static void sync(Configuration cfg, Class<?> cls, String modid, String category, boolean loading, Object instance)
{
for (Field f : cls.getDeclaredFields())
{
if (!Modifier.isPublic(f.getModifiers()))
continue;
//Only the root class may have static fields. Otherwise category tree nodes of the same type would share the
//contained value messing up the sync
if (Modifier.isStatic(f.getModifiers()) != (instance == null))
continue;
if (f.isAnnotationPresent(Config.Ignore.class))
continue;
String comment = null;
Comment ca = f.getAnnotation(Comment.class);
if (ca != null)
comment = NEW_LINE.join(ca.value());
String langKey = modid + "." + (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER) + f.getName().toLowerCase(Locale.ENGLISH);
LangKey la = f.getAnnotation(LangKey.class);
if (la != null)
langKey = la.value();
boolean requiresMcRestart = f.isAnnotationPresent(Config.RequiresMcRestart.class);
boolean requiresWorldRestart = f.isAnnotationPresent(Config.RequiresWorldRestart.class);
if (FieldWrapper.hasWrapperFor(f)) //Wrappers exist for primitives, enums, maps and arrays
{
if (Strings.isNullOrEmpty(category))
throw new RuntimeException("An empty category may not contain anything but objects representing categories!");
try
{
IFieldWrapper wrapper = FieldWrapper.get(instance, f, category);
ITypeAdapter adapt = wrapper.getTypeAdapter();
Property.Type propType = adapt.getType();
for (String key : wrapper.getKeys()) //Iterate the fully qualified property names the field provides
{
String suffix = StringUtils.replaceOnce(key, wrapper.getCategory() + Configuration.CATEGORY_SPLITTER, "");
boolean existed = exists(cfg, wrapper.getCategory(), suffix);
if (!existed || loading) //Creates keys in category specified by the wrapper if new ones are programaticaly added
{
Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter());
adapt.setDefaultValue(property, wrapper.getValue(key));
if (!existed)
adapt.setValue(property, wrapper.getValue(key));
else
wrapper.setValue(key, adapt.getValue(property));
}
else //If the key is not new, sync according to shouldReadFromVar()
{
Property property = property(cfg, wrapper.getCategory(), suffix, propType, adapt.isArrayAdapter());
Object propVal = adapt.getValue(property);
Object mapVal = wrapper.getValue(key);
if (shouldReadFromVar(property, propVal, mapVal))
adapt.setValue(property, mapVal);
else
wrapper.setValue(key, propVal);
}
}
ConfigCategory confCat = cfg.getCategory(wrapper.getCategory());
for (Property property : confCat.getOrderedValues()) //Iterate the properties to check for new data from the config side
{
String key = confCat.getQualifiedName() + Configuration.CATEGORY_SPLITTER + property.getName();
if (!wrapper.handlesKey(key))
continue;
if (loading || !wrapper.hasKey(key))
{
Object value = wrapper.getTypeAdapter().getValue(property);
wrapper.setValue(key, value);
}
}
if (loading)
wrapper.setupConfiguration(cfg, comment, langKey, requiresMcRestart, requiresWorldRestart);
}
catch (Exception e)
{
String format = "Error syncing field '%s' of class '%s'!";
String error = String.format(format, f.getName(), cls.getName());
throw new RuntimeException(error, e);
}
}
else if (f.getType().getSuperclass() != null && f.getType().getSuperclass().equals(Object.class))
{ //If the field extends Object directly, descend the object tree and access the objects members
Object newInstance = null;
try
{
newInstance = f.get(instance);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
//Setup the sub category with its respective name, comment, language key, etc.
String sub = (category.isEmpty() ? "" : category + Configuration.CATEGORY_SPLITTER) + getName(f).toLowerCase(Locale.ENGLISH);
ConfigCategory confCat = cfg.getCategory(sub);
confCat.setComment(comment);
confCat.setLanguageKey(langKey);
confCat.setRequiresMcRestart(requiresMcRestart);
confCat.setRequiresWorldRestart(requiresWorldRestart);
sync(cfg, f.getType(), modid, sub, loading, newInstance);
}
else
{
String format = "Can't handle field '%s' of class '%s': Unknown type.";
String error = String.format(format, f.getName(), cls.getCanonicalName());
throw new RuntimeException(error);
}
}
}
static final Joiner NEW_LINE = Joiner.on('\n');
static final Joiner PIPE = Joiner.on('|');
private static Property property(Configuration cfg, String category, String property, Property.Type type, boolean isList)
{
Property prop = cfg.getCategory(category).get(property);
if (prop == null)
{
if (isList)
prop = new Property(property, new String[0], type);
else
prop = new Property(property, (String)null, type);
cfg.getCategory(category).put(property, prop);
}
return prop;
}
private static boolean exists(Configuration cfg, String category, String property)
{
return cfg.hasCategory(category) && cfg.getCategory(category).containsKey(property);
}
private static boolean shouldReadFromVar(Property property, Object propValue, Object fieldValue)
{
if (!propValue.equals(fieldValue))
{
if (property.hasChanged())
return false;
else
return true;
}
return false;
}
private static String getName(Field f)
{
if (f.isAnnotationPresent(Name.class))
return f.getAnnotation(Name.class).value();
return f.getName();
}
}
@@ -51,12 +51,7 @@ import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Floats;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
import net.minecraftforge.fml.client.config.IConfigElement;
import net.minecraftforge.fml.common.FMLPaths;
import net.minecraftforge.fml.common.Loader;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -112,7 +107,7 @@ public class Configuration
/**
* Create a configuration file for the file given in parameter with the provided config version number.
*/
* /
private void runConfiguration(File file, String configVersion)
{
this.file = file;
@@ -143,16 +138,16 @@ public class Configuration
}
}
}
*/
public Configuration(File file, String configVersion)
{
runConfiguration(file, configVersion);
// runConfiguration(file, configVersion);
}
public Configuration(File file, String configVersion, boolean caseSensitiveCustomCategories)
{
this.caseSensitiveCustomCategories = caseSensitiveCustomCategories;
runConfiguration(file, configVersion);
// runConfiguration(file, configVersion);
}
public Configuration(File file, boolean caseSensitiveCustomCategories)
@@ -1233,13 +1228,13 @@ public class Configuration
* @see GuiConfigEntries.BooleanEntry
* @see GuiConfigEntries.DoubleEntry
* @see GuiConfigEntries.IntegerEntry
*/
* /
public Configuration setCategoryConfigEntryClass(String category, Class<? extends IConfigEntry> clazz)
{
getCategory(category).setConfigEntryClass(clazz);
return this;
}
*/
/**
* Sets the flag for whether or not this category can be edited while a world is running. Care should be taken to ensure
* that only properties that are truly dynamic can be changed from the in-game options menu. Only set this flag to
@@ -1,432 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.config;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import net.minecraftforge.common.config.Config.RangeDouble;
import net.minecraftforge.common.config.Config.RangeInt;
import org.apache.commons.lang3.StringUtils;
import static net.minecraftforge.common.config.ConfigManager.*;
public abstract class FieldWrapper implements IFieldWrapper
{
protected String category, name;
protected Field field;
protected Object instance;
public FieldWrapper(String category, Field field, Object instance)
{
this.instance = instance;
this.field = field;
this.category = category;
this.name = field.getName();
if (field.isAnnotationPresent(Config.Name.class))
this.name = field.getAnnotation(Config.Name.class).value();
this.field.setAccessible(true); // Just in case
}
public static IFieldWrapper get(Object instance, Field field, String category)
{
if (ADAPTERS.get(field.getType()) != null)
return new PrimitiveWrapper(category, field, instance);
else if (Enum.class.isAssignableFrom(field.getType()))
return new EnumWrapper(category, field, instance);
else if (Map.class.isAssignableFrom(field.getType()))
return new MapWrapper(category, field, instance);
else if (field.getType().getSuperclass().equals(Object.class))
throw new RuntimeException("Objects should not be handled by field wrappers");
else
throw new IllegalArgumentException(String.format("Fields of type '%s' are not supported!", field.getType().getCanonicalName()));
}
public static boolean hasWrapperFor(Field field)
{
if (ADAPTERS.get(field.getType()) != null)
return true;
else if (Enum.class.isAssignableFrom(field.getType()))
return true;
else if (Map.class.isAssignableFrom(field.getType()))
return true;
return false;
}
private static class MapWrapper extends FieldWrapper
{
private Map<String, Object> theMap = null;
private Type mType;
private final String baseName;
ITypeAdapter adapter;
@SuppressWarnings("unchecked")
private MapWrapper(String category, Field field, Object instance)
{
super(category, field, instance);
this.baseName = (this.category == null) ? "" : (this.category + ".") + this.name.toLowerCase(Locale.ENGLISH) + ".";
try
{
theMap = (Map<String, Object>) field.get(instance);
}
catch (ClassCastException cce)
{
throw new IllegalArgumentException(String.format("The map '%s' of class '%s' must have the key type String!", field.getName(),
field.getDeclaringClass().getCanonicalName()), cce);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
ParameterizedType type = (ParameterizedType) field.getGenericType();
mType = type.getActualTypeArguments()[1];
this.adapter = ADAPTERS.get(mType);
if (this.adapter == null && mType instanceof GenericArrayType)
{
this.adapter = ADAPTERS.get(ARRAY_REMAP.get(((GenericArrayType)mType).getGenericComponentType())); //J6 seems to have issues, Need to find a better way to translate this. We don't have access to array depth.
}
if (mType instanceof Class && Enum.class.isAssignableFrom((Class<?>)mType))
{
this.adapter = TypeAdapters.Str;
}
if (this.adapter == null)
throw new IllegalArgumentException(String.format("The map '%s' of class '%s' has target values which are neither primitive nor an enum!",
field.getName(), field.getDeclaringClass().getCanonicalName()));
}
@Override
public ITypeAdapter getTypeAdapter()
{
return adapter;
}
@Override
public String[] getKeys()
{
Set<String> keys = theMap.keySet();
String[] keyArray = new String[keys.size()];
Iterator<String> it = keys.iterator();
for (int i = 0; i < keyArray.length; i++)
{
keyArray[i] = this.baseName + it.next();
}
return keyArray;
}
@Override
public Object getValue(String key)
{
return theMap.get(getSuffix(key));
}
@Override
public void setValue(String key, Object value)
{
theMap.put(getSuffix(key), value);
}
@Override
public boolean hasKey(String key)
{
return theMap.containsKey(getSuffix(key));
}
@Override
public boolean handlesKey(String key)
{
if (key == null)
return false;
return key.startsWith(this.baseName);
}
@Override
public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart)
{
ConfigCategory confCat = cfg.getCategory(getCategory());
confCat.setComment(desc);
confCat.setLanguageKey(langKey);
confCat.setRequiresMcRestart(reqMCRestart);
confCat.setRequiresWorldRestart(reqWorldRestart);
}
@Override
public String getCategory()
{
return (this.category == null) ? "" : (this.category + ".") + this.name.toLowerCase(Locale.ENGLISH);
}
/**
* Removes the {@code this.baseName} prefix from the key
* @param key the key to be edited
* @return the keys suffix
*/
private String getSuffix(String key)
{
return StringUtils.replaceOnce(key, this.baseName, "");
}
}
private static class EnumWrapper extends SingleValueFieldWrapper
{
private EnumWrapper(String category, Field field, Object instance)
{
super(category, field, instance);
}
@Override
public ITypeAdapter getTypeAdapter()
{
return TypeAdapters.Str;
}
@Override
public Object getValue(String key)
{
if (!hasKey(key))
throw new IllegalArgumentException("Unsupported Key!");
try
{
@SuppressWarnings("rawtypes")
Enum enu = (Enum) field.get(instance);
return enu.name();
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
@Override
public void setValue(String key, Object value)
{
if (!hasKey(key))
throw new IllegalArgumentException("Unsupported Key!");
@SuppressWarnings({ "unchecked", "rawtypes" })
Enum enu = Enum.valueOf((Class<? extends Enum>) field.getType(), (String) value);
try
{
field.set(instance, enu);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart)
{
super.setupConfiguration(cfg, desc, langKey, reqMCRestart, reqWorldRestart);
Property prop = cfg.getCategory(this.category).get(this.name); // Will be setup in general by ConfigManager
List<String> lst = Lists.newArrayList();
for (Enum e : ((Class<? extends Enum>) field.getType()).getEnumConstants())
lst.add(e.name());
prop.setValidationPattern(Pattern.compile(PIPE.join(lst)));
prop.setValidValues(lst.toArray(new String[0]));
String validValues = NEW_LINE.join(lst);
if (desc != null)
prop.setComment(NEW_LINE.join(new String[] { desc, "Valid values:" }) + "\n" + validValues);
else
prop.setComment("Valid values:" + "\n" + validValues);
}
}
private static class PrimitiveWrapper extends SingleValueFieldWrapper
{
private PrimitiveWrapper(String category, Field field, Object instance)
{
super(category, field, instance);
}
@Override
public ITypeAdapter getTypeAdapter()
{
return ADAPTERS.get(field.getType());
}
@Override
public Object getValue(String key)
{
if (!hasKey(key))
throw new IllegalArgumentException("Unknown key!");
try
{
return field.get(instance);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
@Override
public void setValue(String key, Object value)
{
if (!hasKey(key))
throw new IllegalArgumentException("Unknown key: " + key);
try
{
field.set(instance, value);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
@Override
public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart)
{
super.setupConfiguration(cfg, desc, langKey, reqMCRestart, reqWorldRestart);
Property prop = cfg.getCategory(this.category).get(this.name);
RangeInt ia = field.getAnnotation(RangeInt.class);
if (ia != null)
{
prop.setMinValue(ia.min());
prop.setMaxValue(ia.max());
if (desc != null)
prop.setComment(NEW_LINE.join(new String[] { desc, "Min: " + ia.min(), "Max: " + ia.max() }));
else
prop.setComment(NEW_LINE.join(new String[] { "Min: " + ia.min(), "Max: " + ia.max() }));
}
RangeDouble da = field.getAnnotation(RangeDouble.class);
if (da != null)
{
prop.setMinValue(da.min());
prop.setMaxValue(da.max());
if (desc != null)
prop.setComment(NEW_LINE.join(new String[] { desc, "Min: " + da.min(), "Max: " + da.max() }));
else
prop.setComment(NEW_LINE.join(new String[] { "Min: " + da.min(), "Max: " + da.max() }));
}
}
}
private static abstract class SingleValueFieldWrapper extends FieldWrapper
{
private SingleValueFieldWrapper(String category, Field field, Object instance)
{
super(category, field, instance);
}
@Override
public String[] getKeys()
{
return asArray(this.category + "." + this.name);
}
@Override
public boolean hasKey(String key)
{
return (this.category + "." + this.name).equals(key);
}
@Override
public boolean handlesKey(String key)
{
return hasKey(key);
}
@Override
public void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart)
{
Property prop = cfg.getCategory(this.category).get(this.name); // Will be setup in general by ConfigManager
prop.setComment(desc);
prop.setLanguageKey(langKey);
prop.setRequiresMcRestart(reqMCRestart);
prop.setRequiresWorldRestart(reqWorldRestart);
}
@Override
public String getCategory()
{
return this.category;
}
}
private static <T> T[] asArray(T... in)
{
return in;
}
public static class BeanEntry<K, V> implements Entry<K, V>
{
private K key;
private V value;
public BeanEntry(K key, V value)
{
this.key = key;
this.value = value;
}
@Override
public K getKey()
{
return key;
}
@Override
public V getValue()
{
return value;
}
@Override
public V setValue(V value)
{
throw new UnsupportedOperationException("This is a static bean.");
}
}
}
@@ -1,78 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.config;
/**
* The objects are expected to get their wrapped field, the owning class, instance and category string on initialization.
* In general: The key is the fully qualified property name, where each subcategory is appended with a dot.
* i.e: general.map.isPresent
*/
public interface IFieldWrapper
{
/**
* @return The type adapter to serialize the values returned by getValue. Null if non-primitive.
*/
ITypeAdapter getTypeAdapter();
/**
* @return a list of fully qualified property keys handled by this field
*/
String[] getKeys();
/**
* @param key the fully qualified property key
* @return the value the wrapped field associates with the given key
*/
Object getValue(String key);
/**
* @param key the fully qualified property key
* @param value the target value of the property associated with the key
*/
void setValue(String key, Object value);
/**
* @param key a fully qualified property key
* @return true if the wrapped field contains a property associated with the given key
*/
boolean hasKey(String key);
/**
* @param key a fully qualified property key
* @return true if the wrapped field can save information associated with the given key, false otherwise
*/
boolean handlesKey(String key);
/**
* @param cfg The configuration object holding the properties
* @param desc The properties description
* @param langKey The languageKey of the property, used in GUI
* @param reqMCRestart True, if a change in this property requires a restart of Minecraft
* @param reqWorldRestart True, if the world needs to be reloaded after changes to this property
*/
void setupConfiguration(Configuration cfg, String desc, String langKey, boolean reqMCRestart, boolean reqWorldRestart);
/**
* i.e. general.map in the example above
* @return the category name in which the entries should be saved. This includes the parent categories
*/
String getCategory();
}
@@ -1,53 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.config;
import net.minecraftforge.common.config.Property.Type;
/**
* Abstracts the types of properties away. Higher level logic must prevent invalid data types.
*/
interface ITypeAdapter
{
/**
* Assigns the default value to the property
* @param property the property whose default value will be assigned
* @param value the default value
*/
void setDefaultValue(Property property, Object value);
/**
* Sets the properties value.
* @param property the property whose value will be set
* @param value the set value
*/
void setValue(Property property, Object value);
/**
* Retrieves the properties value
* @param prop the property whose value will be retrieved
* @return the properties value
*/
Object getValue(Property prop);
Type getType();
boolean isArrayAdapter();
}
@@ -23,13 +23,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Pattern;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;
import net.minecraftforge.fml.client.config.GuiConfigEntries.IConfigEntry;
import net.minecraftforge.fml.client.config.GuiEditArray;
import net.minecraftforge.fml.client.config.GuiEditArrayEntries;
import net.minecraftforge.fml.client.config.GuiEditArrayEntries.IArrayEntry;
import net.minecraftforge.fml.client.config.IArrayEntry;
import net.minecraftforge.fml.client.config.IConfigElement;
import net.minecraftforge.fml.client.config.IConfigEntry;
public class Property
{
@@ -1,869 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.config;
//=========================================================
// Run away thar' be dragons!
//=========================================================
import java.util.Arrays;
import com.google.common.primitives.Booleans;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Floats;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Shorts;
import net.minecraftforge.common.config.Property.Type;
class TypeAdapters
{
/*
* boolean, boolean[], Boolean, Boolean[]
* float, float[], Float, Float[]
* double, double[], Double, Double[]
* byte, byte[], Byte, Byte[]
* char, char[], Character, Character[]
* short, short[], Short, Short[]
* int, int[], Integer, Integer[]
* String, String[]
*/
static ITypeAdapter bool = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return prop.getBoolean();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Boolean)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Boolean)value);
}
@Override
public Type getType()
{
return Type.BOOLEAN;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter boolA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return prop.getBooleanList();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues((boolean[])value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValues((boolean[])value);
}
@Override
public Type getType()
{
return Type.BOOLEAN;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Bool = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Boolean.valueOf(prop.getBoolean());
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Boolean)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Boolean)value);
}
@Override
public Type getType()
{
return Type.BOOLEAN;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter BoolA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Booleans.asList(prop.getBooleanList()).toArray(new Boolean[prop.getBooleanList().length]);
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Booleans.toArray(Arrays.asList((Boolean[]) value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Booleans.toArray(Arrays.asList((Boolean[]) value)));
}
@Override
public Type getType()
{
return Type.BOOLEAN;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter flt = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return (float)prop.getDouble();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Float)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Float)value);
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter fltA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Floats.toArray(Doubles.asList(prop.getDoubleList()));
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Doubles.toArray(Floats.asList((float[])value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Doubles.toArray(Floats.asList((float[])value)));
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Flt = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Float.valueOf((float)prop.getDouble());
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Float)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Float)value);
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter FltA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Floats.asList(Floats.toArray(Doubles.asList(prop.getDoubleList()))).toArray(new Float[prop.getDoubleList().length]);
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Doubles.toArray(Arrays.asList((Float[])value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Doubles.toArray(Arrays.asList((Float[])value)));
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter dbl = new ITypeAdapter() {
@Override
public Object getValue(Property prop)
{
return prop.getDouble();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Double)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Double)value);
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter dblA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return prop.getDoubleList();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues((double[])value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValues((double[])value);
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Dbl = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Double.valueOf(prop.getDouble());
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Double)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Double) value);
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter DblA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Doubles.asList(prop.getDoubleList()).toArray(new Double[prop.getDoubleList().length]);
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Doubles.toArray(Arrays.asList((Double[])value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Doubles.toArray(Arrays.asList((Double[])value)));
}
@Override
public Type getType()
{
return Type.DOUBLE;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter byt = new ITypeAdapter() {
@Override
public Object getValue(Property prop)
{
return (byte)prop.getInt();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Byte)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Byte)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter bytA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Bytes.toArray(Ints.asList(prop.getIntList()));
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Ints.toArray(Bytes.asList((byte[])value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Ints.toArray(Bytes.asList((byte[])value)));
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Byt = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Byte.valueOf((byte)prop.getInt());
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Byte)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Byte)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter BytA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Bytes.asList(Bytes.toArray(Ints.asList(prop.getIntList()))).toArray(new Byte[prop.getIntList().length]);
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Ints.toArray(Arrays.asList((Byte[]) value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Ints.toArray(Arrays.asList((Byte[]) value)));
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter chr = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return (char)prop.getInt();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Character)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Character)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter chrA = new ITypeAdapter() {
private int[] toPrim(char[] v) {
if (v == null) return new int[0];
int[] ret = new int[v.length];
for (int x = 0; x < v.length; x++)
ret[x] = v[x];
return ret;
}
@Override
public Object getValue(Property prop) {
int[] v = prop.getIntList();
char[] ret = new char[v.length];
for (int x = 0; x < v.length; x++)
ret[x] = (char)v[x];
return ret;
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(toPrim((char[])value));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(toPrim((char[])value));
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Chr = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Character.valueOf((char)prop.getInt());
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Character)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Character)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter ChrA = new ITypeAdapter() {
private int[] toPrim(Character[] v) {
if (v == null) return new int[0];
int[] ret = new int[v.length];
for (int x = 0; x < v.length; x++)
ret[x] = v[x] == null ? 0 : v[x];
return ret;
}
@Override
public Object getValue(Property prop) {
int[] v = prop.getIntList();
Character[] ret = new Character[v.length];
for (int x = 0; x < v.length; x++)
ret[x] = Character.valueOf((char)v[x]);
return ret;
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(toPrim((Character[])value));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(toPrim((Character[]) value));
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter shrt = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return (short)prop.getInt();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Short)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Short)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter shrtA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Shorts.toArray(Ints.asList(prop.getIntList()));
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Ints.toArray(Shorts.asList((short[])value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Ints.toArray(Shorts.asList((short[])value)));
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Shrt = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Short.valueOf((short)prop.getInt());
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Short)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Short)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter ShrtA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
int[] v = prop.getIntList();
Short[] ret = new Short[v.length];
for (int x = 0; x < ret.length; x++)
ret[x] = Short.valueOf((short)v[x]);
return ret;
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Ints.toArray(Arrays.asList((Short[])value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Ints.toArray(Arrays.asList((Short[])value)));
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter int_ = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return prop.getInt();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Integer)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Integer)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter intA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return prop.getIntList();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues((int[])value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValues((int[])value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Int = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return (Integer)prop.getInt();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((Integer)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((Integer)value);
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter IntA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return Ints.asList(prop.getIntList()).toArray(new Integer[prop.getIntList().length]);
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues(Ints.toArray(Arrays.asList((Integer[])value)));
}
@Override
public void setValue(Property property, Object value)
{
property.setValues(Ints.toArray(Arrays.asList((Integer[])value)));
}
@Override
public Type getType()
{
return Type.INTEGER;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
static ITypeAdapter Str = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return prop.getString();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValue((String)value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValue((String)value);
}
@Override
public Type getType()
{
return Type.STRING;
}
@Override
public boolean isArrayAdapter()
{
return false;
}
};
static ITypeAdapter StrA = new ITypeAdapter() {
@Override
public Object getValue(Property prop) {
return prop.getStringList();
}
@Override
public void setDefaultValue(Property property, Object value)
{
property.setDefaultValues((String[])value);
}
@Override
public void setValue(Property property, Object value)
{
property.setValues((String[])value);
}
@Override
public Type getType()
{
return Type.STRING;
}
@Override
public boolean isArrayAdapter()
{
return true;
}
};
}
@@ -3,12 +3,16 @@ package net.minecraftforge.common.extensions;
import javax.annotation.Nullable;
import net.minecraft.world.World;
import net.minecraft.world.dimension.Dimension;
import net.minecraft.world.dimension.NetherDimension;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.IRenderHandler;
public interface IForgeDimension
{
default Dimension getDimension() { return (Dimension) this; }
/**
* Called from {@link World#initCapabilities()}, to gather capabilities for this
* world. It's safe to access world here since this is called after world is
@@ -26,6 +30,22 @@ public interface IForgeDimension
return null;
}
/**
* The dimension's movement factor.
* Whenever a player or entity changes dimension from world A to world B, their coordinates are multiplied by
* worldA.provider.getMovementFactor() / worldB.provider.getMovementFactor()
* Example: Overworld factor is 1, nether factor is 8. Traveling from overworld to nether multiplies coordinates by 1/8.
* @return The movement factor
*/
default double getMovementFactor()
{
if (getDimension() instanceof NetherDimension)
{
return 8.0;
}
return 1.0;
}
/**
* Sets the providers current dimension ID, used in default getSaveFolder()
* Added to allow default providers to be registered for multiple dimensions.
@@ -0,0 +1,16 @@
package net.minecraftforge.common.extensions;
import java.io.File;
import net.minecraft.world.WorldServer;
import net.minecraft.world.chunk.storage.AnvilChunkLoader;
public interface IForgeWorldServer extends IForgeWorld
{
default WorldServer getWorldServer() { return (WorldServer) this; }
default File getChunkSaveLocation()
{
return ((AnvilChunkLoader) getWorldServer().getChunkProvider().chunkLoader).chunkSaveLocation;
}
}
@@ -27,7 +27,7 @@ import org.apache.logging.log4j.Logger;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/* TODO fluids
public class FluidIdRegistryMessageHandler extends SimpleChannelInboundHandler<ForgeMessage.FluidIdMapMessage> {
private static final Logger LOGGER = LogManager.getLogger();
@@ -44,3 +44,4 @@ public class FluidIdRegistryMessageHandler extends SimpleChannelInboundHandler<F
}
}
*/
@@ -70,7 +70,7 @@ public abstract class ForgeMessage {
providerId = new String(data, StandardCharsets.UTF_8);
}
}
/* TODO fluids
public static class FluidIdMapMessage extends ForgeMessage {
BiMap<Fluid, Integer> fluidIds = HashBiMap.create();
Set<String> defaultFluids = Sets.newHashSet();
@@ -117,7 +117,7 @@ public abstract class ForgeMessage {
}
}
}
*/
abstract void toBytes(ByteBuf bytes);
abstract void fromBytes(ByteBuf bytes);
}
@@ -18,7 +18,7 @@
*/
package net.minecraftforge.common.network;
/* TODO handshake
import java.util.EnumMap;
import net.minecraftforge.api.distmarker.OnlyIn;
@@ -56,3 +56,4 @@ public class ForgeNetworkHandler
clientChannel.pipeline().addAfter(handlerName, "FluidIdRegistryHandler", new FluidIdRegistryMessageHandler());
}
}
*/
@@ -18,7 +18,7 @@
*/
package net.minecraftforge.common.network;
/* TODO handshake
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import net.minecraftforge.fml.common.network.FMLIndexedMessageToMessageCodec;
@@ -41,3 +41,4 @@ public class ForgeRuntimeCodec extends FMLIndexedMessageToMessageCodec<ForgeMess
msg.fromBytes(source);
}
}
*/
@@ -18,7 +18,7 @@
*/
package net.minecraftforge.common.network;
/* TODO handshake
import net.minecraftforge.fml.common.network.NetworkHandshakeEstablished;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
@@ -36,3 +36,4 @@ public class ServerToClientConnectionEstablishedHandler extends ChannelInboundHa
ctx.fireUserEventTriggered(evt);
}
}
*/
@@ -38,15 +38,16 @@ import net.minecraft.block.state.BlockState;
import net.minecraft.block.state.IBlockState;
import net.minecraft.state.AbstractStateHolder;
import net.minecraft.state.IProperty;
import net.minecraft.state.IStateHolder;
import net.minecraft.state.StateContainer;
public class ExtendedBlockState extends StateContainer<Block, IBlockState>
// TODO Extended states gotta go, I doubt this works at all
public class ExtendedStateContainer<O, S extends IExtendedState<S>> extends StateContainer<O, S>
{
private final ImmutableSet<IUnlistedProperty<?>> unlistedProperties;
public <A extends AbstractStateHolder<Block, IBlockState>> ExtendedBlockState(Block blockIn, StateContainer.IFactory<Block, IBlockState, ?> stateFactory, net.minecraft.state.IProperty<?>[] properties, IUnlistedProperty<?>[] unlistedProperties)
public <A extends AbstractStateHolder<O, S>> ExtendedStateContainer(O blockIn, StateContainer.IFactory<O, S, A> stateFactory, net.minecraft.state.IProperty<?>[] properties, IUnlistedProperty<?>[] unlistedProperties)
{
super(blockIn, stateFactory, buildListedMap(properties));// TODO Unlisted properties?, buildUnlistedMap(unlistedProperties));
super(blockIn, getProxyFactory(unlistedProperties, stateFactory), buildListedMap(properties));// TODO Unlisted properties?, buildUnlistedMap(unlistedProperties));
ImmutableSet.Builder<IUnlistedProperty<?>> builder = ImmutableSet.builder();
for(IUnlistedProperty<?> property : unlistedProperties)
{
@@ -54,6 +55,15 @@ public class ExtendedBlockState extends StateContainer<Block, IBlockState>
}
this.unlistedProperties = builder.build();
}
private static <O, S extends IExtendedState<S>, A extends AbstractStateHolder<O, S>>
StateContainer.IFactory<O, S, AbstractStateHolder<O,S>> getProxyFactory(IUnlistedProperty<?>[] unlistedProperties, StateContainer.IFactory<O, S, A> proxy)
{
return (o, props) -> {
if (unlistedProperties == null || unlistedProperties.length == 0) return proxy.create(o, props);
return new ExtendedStateHolder<O, S>(o, props, buildUnlistedMap(unlistedProperties), null);
};
}
public Collection<IUnlistedProperty<?>> getUnlistedProperties()
{
@@ -75,33 +85,25 @@ public class ExtendedBlockState extends StateContainer<Block, IBlockState>
return builder.build();
}
@Override
@Nonnull
protected StateImplementation createState(@Nonnull Block block, @Nonnull ImmutableMap<IProperty<?>, Comparable<?>> properties, @Nullable ImmutableMap<IUnlistedProperty<?>, Optional<?>> unlistedProperties)
{
if (unlistedProperties == null || unlistedProperties.isEmpty()) return super.createState(block, properties, unlistedProperties);
return new ExtendedStateImplementation(block, properties, unlistedProperties, null, null);
}
protected static class ExtendedStateImplementation extends StateImplementation implements IExtendedBlockState
protected static class ExtendedStateHolder<O, S extends IExtendedState<S>> extends AbstractStateHolder<O, S> implements IExtendedState<S>
{
private final ImmutableMap<IUnlistedProperty<?>, Optional<?>> unlistedProperties;
private IBlockState cleanState;
private S cleanState;
protected ExtendedStateImplementation(Block block, ImmutableMap<IProperty<?>, Comparable<?>> properties, ImmutableMap<IUnlistedProperty<?>, Optional<?>> unlistedProperties, @Nullable ImmutableTable<IProperty<?>, Comparable<?>, IBlockState> table, IBlockState clean)
protected ExtendedStateHolder(O block, ImmutableMap<IProperty<?>, Comparable<?>> properties, ImmutableMap<IUnlistedProperty<?>, Optional<?>> unlistedProperties, S clean)
{
super(block, properties, table);
super(block, properties);
this.unlistedProperties = unlistedProperties;
this.cleanState = clean == null ? this : clean;
this.cleanState = clean == null ? (S) this : clean;
}
@Override
@Nonnull
public <T extends Comparable<T>, V extends T> IBlockState withProperty(@Nonnull IProperty<T> property, @Nonnull V value)
public <T extends Comparable<T>, V extends T> S func_206870_a(@Nonnull IProperty<T> property, @Nonnull V value)
{
IBlockState clean = super.withProperty(property, value);
S clean = super.func_206870_a(property, value);
if (clean == this.cleanState) {
return this;
return (S) this;
}
if (this == this.cleanState)
@@ -109,24 +111,24 @@ public class ExtendedBlockState extends StateContainer<Block, IBlockState>
return clean;
}
return new ExtendedStateImplementation(getBlock(), clean.getProperties(), unlistedProperties, ((StateImplementation)clean).getPropertyValueTable(), this.cleanState);
return (S) new ExtendedStateHolder(field_206876_a, ((BlockState)clean).func_206871_b(), unlistedProperties, this.cleanState);
}
@Override
public <V> IExtendedBlockState withProperty(IUnlistedProperty<V> property, @Nullable V value)
public <V> S withProperty(IUnlistedProperty<V> property, @Nullable V value)
{
Optional<?> oldValue = unlistedProperties.get(property);
if (oldValue == null)
{
throw new IllegalArgumentException("Cannot set unlisted property " + property + " as it does not exist in " + getBlock().getBlockState());
throw new IllegalArgumentException("Cannot set unlisted property " + property + " as it does not exist in " + this);
}
if (Objects.equals(oldValue.orElse(null), value))
{
return this;
return (S) this;
}
if (!property.isValid(value))
{
throw new IllegalArgumentException("Cannot set unlisted property " + property + " to " + value + " on block " + Block.REGISTRY.getNameForObject(getBlock()) + ", it is not an allowed value");
throw new IllegalArgumentException("Cannot set unlisted property " + property + " to " + value + " on object " + field_206876_a + ", it is not an allowed value");
}
boolean clean = true;
ImmutableMap.Builder<IUnlistedProperty<?>, Optional<?>> builder = ImmutableMap.builder();
@@ -139,9 +141,9 @@ public class ExtendedBlockState extends StateContainer<Block, IBlockState>
}
if (clean)
{ // no dynamic properties, lookup normal state
return (IExtendedBlockState) cleanState;
return (S) cleanState;
}
return new ExtendedStateImplementation(getBlock(), getProperties(), builder.build(), propertyValueTable, this.cleanState);
return (S) new ExtendedStateHolder(field_206876_a, func_206871_b(), builder.build(), this.cleanState);
}
@Override
@@ -157,7 +159,7 @@ public class ExtendedBlockState extends StateContainer<Block, IBlockState>
Optional<?> value = unlistedProperties.get(property);
if (value == null)
{
throw new IllegalArgumentException("Cannot get unlisted property " + property + " as it does not exist in " + getBlock().getBlockState());
throw new IllegalArgumentException("Cannot get unlisted property " + property + " as it does not exist in " + this);
}
return property.getType().cast(value.orElse(null));
}
@@ -168,7 +170,7 @@ public class ExtendedBlockState extends StateContainer<Block, IBlockState>
}
@Override
public IBlockState getClean()
public S getClean()
{
return cleanState;
}
@@ -1,40 +1,8 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.property;
import java.util.Collection;
import net.minecraft.block.state.IBlockState;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
public interface IExtendedBlockState extends IBlockState
public interface IExtendedBlockState extends IExtendedState<IBlockState>, IBlockState
{
Collection<IUnlistedProperty<?>> getUnlistedNames();
<V>V getValue(IUnlistedProperty<V> property);
<V>IExtendedBlockState withProperty(IUnlistedProperty<V> property, V value);
ImmutableMap<IUnlistedProperty<?>, Optional<?>> getUnlistedProperties();
IBlockState getClean();
}
@@ -17,11 +17,25 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.util;
package net.minecraftforge.common.property;
import net.minecraft.util.datafix.IDataFixer;
import java.util.Collection;
public interface IDataFixerData extends IDataFixer
import net.minecraft.block.state.IBlockState;
import net.minecraft.state.IStateHolder;
import java.util.Optional;
import com.google.common.collect.ImmutableMap;
public interface IExtendedState<C> extends IStateHolder<C>
{
int getVersion(String mod);
Collection<IUnlistedProperty<?>> getUnlistedNames();
<V>V getValue(IUnlistedProperty<V> property);
<V>C withProperty(IUnlistedProperty<V> property, V value);
ImmutableMap<IUnlistedProperty<?>, Optional<?>> getUnlistedProperties();
C getClean();
}
@@ -28,7 +28,6 @@ import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.registries.ForgeRegistries;
import javax.annotation.Nullable;
@@ -54,7 +53,7 @@ public class BlockSnapshot
@Nullable
private WeakReference<World> world;
private final ResourceLocation registryName;
private final int meta;
private final int meta = 0; // TODO BlockSnapshot needs a total refactor for the absence of metadata
public BlockSnapshot(World world, BlockPos pos, IBlockState state)
{
@@ -68,7 +67,6 @@ public class BlockSnapshot
this.pos = pos.toImmutable();
this.setReplacedBlock(state);
this.registryName = state.getBlock().getRegistryName();
this.meta = state.getBlock().getMetaFromState(state);
this.setFlag(3);
this.nbt = nbt;
if (DEBUG)
@@ -99,7 +97,6 @@ public class BlockSnapshot
this.pos = pos.toImmutable();
this.setFlag(flag);
this.registryName = registryName;
this.meta = meta;
this.nbt = nbt;
}
@@ -143,7 +140,7 @@ public class BlockSnapshot
World world = this.world != null ? this.world.get() : null;
if (world == null)
{
world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(getDimId());
world = null; // TODO Server static access? FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(getDimId());
this.world = new WeakReference<World>(world);
}
return world;
@@ -153,7 +150,7 @@ public class BlockSnapshot
{
if (this.replacedBlock == null)
{
this.replacedBlock = ForgeRegistries.BLOCKS.getValue(getRegistryName()).getStateFromMeta(getMeta());
this.replacedBlock = ForgeRegistries.BLOCKS.getValue(getRegistryName()).func_196257_b(getMeta());
}
return this.replacedBlock;
}
@@ -161,7 +158,7 @@ public class BlockSnapshot
@Nullable
public TileEntity getTileEntity()
{
return getNbt() != null ? TileEntity.create(getWorld(), getNbt()) : null;
return getNbt() != null ? TileEntity.func_203403_c(getNbt()) : null;
}
public boolean restore()
@@ -184,7 +181,7 @@ public class BlockSnapshot
IBlockState current = getCurrentBlock();
IBlockState replaced = getReplacedBlock();
if (current.getBlock() != replaced.getBlock() || current.getBlock().getMetaFromState(current) != replaced.getBlock().getMetaFromState(replaced))
if (current != replaced)
{
if (force)
{
@@ -212,15 +209,15 @@ public class BlockSnapshot
if (DEBUG)
{
System.out.printf("Restored BlockSnapshot with data [World: %s ][Location: %d,%d,%d ][Meta: %d ][Block: %s ][TileEntity: %s ][force: %s ][notifyNeighbors: %s]", world.getWorldInfo().getWorldName(), pos.getX(), pos.getY(), pos.getZ(), replaced.getBlock().getMetaFromState(replaced), replaced.getBlock().delegate.name(), te, force, notifyNeighbors);
System.out.printf("Restored BlockSnapshot with data [World: %s ][Location: %d,%d,%d ][State: %s ][Block: %s ][TileEntity: %s ][force: %s ][notifyNeighbors: %s]", world.getWorldInfo().getWorldName(), pos.getX(), pos.getY(), pos.getZ(), replaced, replaced.getBlock().delegate.name(), te, force, notifyNeighbors);
}
return true;
}
public void writeToNBT(NBTTagCompound compound)
{
compound.setString("blockMod", getRegistryName().getResourceDomain());
compound.setString("blockName", getRegistryName().getResourcePath());
compound.setString("blockMod", getRegistryName().getNamespace());
compound.setString("blockName", getRegistryName().getPath());
compound.setInteger("posX", getPos().getX());
compound.setInteger("posY", getPos().getY());
compound.setInteger("posZ", getPos().getZ());
@@ -1,185 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.util;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.datafix.DataFixer;
import net.minecraft.util.datafix.FixTypes;
import net.minecraft.util.datafix.IDataWalker;
import net.minecraft.util.datafix.IFixType;
import net.minecraft.util.datafix.IFixableData;
public class CompoundDataFixer extends DataFixer
{
private final ModFixs vanilla;
private final Map<String, ModFixs> modFixers = Maps.newHashMap();
private final Map<IFixType, List<IDataWalker>> walkers = Maps.newHashMap();
public CompoundDataFixer(DataFixer vanilla)
{
super(0);
this.vanilla = init("minecraft", vanilla.version);
}
@Override
public NBTTagCompound process(IFixType type, NBTTagCompound nbt)
{
final Map<String, Integer>versions = getVersions(nbt);
final int mcversion = versions.get("minecraft") == null ? -1 : versions.get("minecraft");
final IDataFixerData holder = new IDataFixerData()
{
@Override
public NBTTagCompound process(IFixType type, NBTTagCompound nbt, int version)
{
for (Entry<String, ModFixs> e : modFixers.entrySet())
{
// This is a potential performance hot spot. As it walks all the data for all
// of the fixers... But with the vanilla api there isn't a way to pass down
// the mod specific version numbers, so redundant.. but not hacky...
//Actually, this wont work as the data walkers take versions into account...
ModFixs fixer = e.getValue();
int ver = getVersion(e.getKey());
if (ver < fixer.version)
{
for (IFixableData fix : fixer.getFixes(type))
{
if (fix.getFixVersion() > ver)
nbt = fix.fixTagCompound(nbt);
}
for (IDataWalker walker : getWalkers(type))
nbt = walker.process(this, nbt, version); //We pass in the holder, in case a walker wants to know a mod version
}
}
return nbt;
}
@Override
public int getVersion(String mod)
{
Integer ret = versions.get(mod);
return ret == null ? -1 : ret;
}
};
return holder.process(type, nbt, mcversion);
}
@Override
@Deprecated //MODDERS DO NOT CALL DIRECTLY! Only use from DataWalker!
public NBTTagCompound process(IFixType type, NBTTagCompound nbt, int mcversion)
{
if (type != FixTypes.OPTIONS) //Options are vanilla only
throw new IllegalStateException("Do not call recursive process directly on DataFixer!");
for (IFixableData fix : vanilla.getFixes(type))
{
if (fix.getFixVersion() > mcversion)
nbt = fix.fixTagCompound(nbt);
}
//Options is a hack, and doesn't have any nested components
//for (IDataWalker walker : getWalkers(type))
// nbt = walker.process(this, nbt, version);
return nbt;
}
private List<IDataWalker> getWalkers(IFixType type)
{
return walkers.computeIfAbsent(type, k -> Lists.newArrayList());
}
@Override
@Deprecated //Modders do not use this, this will register you as vanilla. Use the ModID version below.
public void registerFix(IFixType type, IFixableData fixable)
{
vanilla.registerFix(type, fixable);
}
@Override
@Deprecated //Modders do not use this, use add below, To better allow custom fix types.
public void registerWalker(FixTypes type, IDataWalker walker)
{
registerVanillaWalker(type, walker);
}
@Override
public void registerVanillaWalker(IFixType type, IDataWalker walker)
{
getWalkers(type).add(walker);
}
private void validateModId(String mod)
{
//String current = Loader.instance().activeModContainer() == null ? "minecraft" : Loader.instance().activeModContainer().getModId();
//Test active modid?
if (!mod.equals(mod.toLowerCase(Locale.ENGLISH)))
throw new IllegalArgumentException("Mod ID is not lower case: " + mod);
if (mod.length() > 64)
throw new IllegalArgumentException("Mod ID is to long: " + mod);
}
/**
* Initialize your mod specific data fixer.
*
* @param modid You mod id, must be lower case.
* @param version The current data version of your mod
*/
public ModFixs init(String modid, int version)
{
validateModId(modid);
if (modFixers.containsKey(modid))
throw new IllegalStateException("Attempted to initalize DataFixer for " + modid + " twice");
ModFixs ret = new ModFixs(modid, version);
modFixers.put(modid, ret);
return ret;
}
private Map<String, Integer> getVersions(NBTTagCompound nbt)
{
Map<String, Integer> ret = Maps.newHashMap();
ret.put("minecraft", nbt.hasKey("DataVersion", 99) ? nbt.getInteger("DataVersion") : -1);
if (nbt.hasKey("ForgeDataVersion", 10))
{
NBTTagCompound sub = nbt.getCompoundTag("ForgeDataVersion");
for (String key : sub.getKeySet())
{
ret.put(key, sub.hasKey(key, 99) ? sub.getInteger(key) : -1);
}
}
return ret;
}
public void writeVersionData(NBTTagCompound nbt)
{
//nbt.setInteger("DataVersion", vanilla.version);
NBTTagCompound sub = new NBTTagCompound();
nbt.setTag("ForgeDataVersion", sub);
for (ModFixs mod : modFixers.values())
sub.setInteger(mod.mod, mod.version);
}
}
@@ -1,85 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.util;
import java.lang.reflect.*;
import java.util.*;
import java.util.function.BiPredicate;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import net.minecraftforge.fml.common.EnhancedRuntimeException;
import org.apache.commons.lang3.ArrayUtils;
import javax.annotation.Nullable;
public class EnumHelper
{
/*
* Everything below this is found at the site below, and updated to be able to compile in Eclipse/Java 1.6+
* Also modified for use in decompiled code.
* Found at: http://niceideas.ch/roller2/badtrash/entry/java_create_enum_instances_dynamically
*/
private static < T extends Enum<? >> T makeEnum(Class<T> enumClass, @Nullable String value, int ordinal, Class<?>[] additionalTypes, @Nullable Object[] additionalValues) throws Exception
{
//new Enum(name, values.size() + 1, params)
}
private static void blankField(Class<?> enumClass, String fieldName) throws Exception
{
for (Field field : Class.class.getDeclaredFields())
{
if (field.getName().contains(fieldName))
{
field.setAccessible(true);
field.set(enumClass, null);
break;
}
}
}
//Class holds caches of the enum constants used for Enum.valueOf() and reflection magic. So we need to invalidate those caches when we add something new. They will automtically be re-built.
public static void cleanEnumCache(Class<?> enumClass) throws Exception
{
blankField(enumClass, "enumConstantDirectory");
blankField(enumClass, "enumConstants");
}
@SuppressWarnings({ "unchecked", "serial" })
@Nullable
private static <T extends Enum<?> & IExpandableEnum<?>> T addEnum(boolean test, final Class<T> enumType, T newValue)
{
try
{
T[] previousValues = enumType.getEnumConstants();
T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
newValue.__set_values__(ArrayUtils.add(previousValues, newValue));
cleanEnumCache(enumType);
return newValue;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
@@ -22,7 +22,6 @@ package net.minecraftforge.common.util;
import com.mojang.authlib.GameProfile;
import net.minecraft.entity.Entity;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.client.CPacketClientSettings;
@@ -39,11 +38,10 @@ public class FakePlayer extends EntityPlayerMP
{
public FakePlayer(WorldServer world, GameProfile name)
{
super(FMLCommonHandler.instance().getMinecraftServerInstance(), world, name, new PlayerInteractionManager(world));
super(world.getMinecraftServer(), world, name, new PlayerInteractionManager(world));
}
@Override public Vec3d getPositionVector(){ return new Vec3d(0, 0, 0); }
@Override public boolean canUseCommand(int i, String s){ return false; }
@Override public void sendStatusMessage(ITextComponent chatComponent, boolean actionBar){}
@Override public void sendMessage(ITextComponent component) {}
@Override public void addStat(StatBase par1StatBase, int par2){}
@@ -22,7 +22,6 @@ package net.minecraftforge.common.util;
import net.minecraft.entity.Entity;
import net.minecraft.world.Teleporter;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
/**
* Interface for handling the placement of entities during dimension change.
@@ -36,8 +36,9 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.nbt.JsonToNBT;
import net.minecraft.nbt.NBTException;
import net.minecraft.nbt.NBTTagCompound;
import javax.annotation.Nullable;
@@ -103,7 +104,7 @@ public class JsonUtils
try
{
return JsonToNBT.getTagFromJson(net.minecraft.util.JsonUtils.getString(json, key));
} catch (NBTException e)
} catch (CommandSyntaxException e)
{
throw new JsonSyntaxException("Malformed NBT tag", e);
}
@@ -1,78 +0,0 @@
/*
* Minecraft Forge
* Copyright (c) 2016-2018.
*
* This library 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 version 2.1
* of the License.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.minecraftforge.common.util;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import net.minecraft.util.datafix.IFixType;
import net.minecraft.util.datafix.IFixableData;
public class ModFixs
{
private static final Logger LOGGER = LogManager.getLogger();
final String mod;
final int version;
private final Map<IFixType, List<IFixableData>> fixes = Maps.newHashMap();
ModFixs(String mod, int version)
{
this.mod = mod;
this.version = version;
}
public List<IFixableData> getFixes(IFixType type)
{
return this.fixes.computeIfAbsent(type, k -> Lists.newArrayList());
}
public void registerFix(IFixType type, IFixableData fixer)
{
List<IFixableData> list = getFixes(type);
int ver = fixer.getFixVersion();
if (ver > this.version)
{
LOGGER.warn("[{}] Ignored fix registered for version: {} as the DataVersion of the game is: {}", mod, ver, this.version);
return;
}
if (!list.isEmpty() && list.get(list.size()-1).getFixVersion() > ver)
{
for (int x = 0; x < list.size(); ++x)
{
if (list.get(x).getFixVersion() > ver)
{
list.add(x, fixer);
break;
}
}
}
else
list.add(fixer);
}
}
@@ -45,7 +45,6 @@ public class PacketUtil
{
buffer.writeShort(Item.getIdFromItem(stack.getItem()));
buffer.writeByte(stack.getCount());
buffer.writeShort(stack.getMetadata());
NBTTagCompound nbttagcompound = null;
if (stack.getItem().isDamageable() || stack.getItem().getShareTag())