mirror of
https://github.com/MinecraftForge/MinecraftForge.git
synced 2026-11-20 04:09:51 +00:00
Step 2: The Reformation
This commit is contained in:
1 parent
9332673944
commit
797399ff7f
198 files changed
+24
-10
No files matched your search
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* This software is provided under the terms of the Minecraft Forge Public
|
||||
* License v1.0.
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import net.minecraft.stats.Achievement;
|
||||
|
||||
public class AchievementPage
|
||||
{
|
||||
private String name;
|
||||
private LinkedList<Achievement> achievements;
|
||||
|
||||
public AchievementPage(String name, Achievement... achievements)
|
||||
{
|
||||
this.name = name;
|
||||
this.achievements = new LinkedList<Achievement>(Arrays.asList(achievements));
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public List<Achievement> getAchievements()
|
||||
{
|
||||
return achievements;
|
||||
}
|
||||
|
||||
private static LinkedList<AchievementPage> achievementPages = new LinkedList<AchievementPage>();
|
||||
|
||||
/**
|
||||
* Registers an achievement page.
|
||||
* @param page The page.
|
||||
*/
|
||||
public static void registerAchievementPage(AchievementPage page)
|
||||
{
|
||||
if (getAchievementPage(page.getName()) != null)
|
||||
{
|
||||
throw new RuntimeException("Duplicate achievement page name \"" + page.getName() + "\"!");
|
||||
}
|
||||
achievementPages.add(page);
|
||||
}
|
||||
|
||||
/**
|
||||
* Will return an achievement page by its index on the list.
|
||||
* @param index The page's index.
|
||||
* @return the achievement page corresponding to the index or null if invalid index
|
||||
*/
|
||||
public static AchievementPage getAchievementPage(int index)
|
||||
{
|
||||
return achievementPages.get(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Will return an achievement page by its name.
|
||||
* @param name The page's name.
|
||||
* @return the achievement page with the given name or null if no such page
|
||||
*/
|
||||
public static AchievementPage getAchievementPage(String name)
|
||||
{
|
||||
for (AchievementPage page : achievementPages)
|
||||
{
|
||||
if (page.getName().equals(name))
|
||||
{
|
||||
return page;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Will return the list of achievement pages.
|
||||
* @return the list's size
|
||||
*/
|
||||
public static Set<AchievementPage> getAchievementPages()
|
||||
{
|
||||
return new HashSet<AchievementPage>(achievementPages);
|
||||
}
|
||||
|
||||
/**
|
||||
* Will return whether an achievement is in any page or not.
|
||||
* @param achievement The achievement.
|
||||
*/
|
||||
public static boolean isAchievementInPages(Achievement achievement)
|
||||
{
|
||||
for (AchievementPage page : achievementPages)
|
||||
{
|
||||
if (page.getAchievements().contains(achievement))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static String getTitle(int index)
|
||||
{
|
||||
return index == -1 ? "Minecraft" : getAchievementPage(index).getName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
import net.minecraft.world.biome.*;
|
||||
import net.minecraftforge.event.terraingen.DeferredBiomeDecorator;
|
||||
import static net.minecraft.world.biome.BiomeGenBase.*;
|
||||
import static net.minecraftforge.common.BiomeDictionary.Type.*;
|
||||
|
||||
public class BiomeDictionary
|
||||
{
|
||||
public enum Type
|
||||
{
|
||||
FOREST,
|
||||
PLAINS,
|
||||
MOUNTAIN,
|
||||
HILLS,
|
||||
SWAMP,
|
||||
WATER,
|
||||
DESERT,
|
||||
FROZEN,
|
||||
JUNGLE,
|
||||
WASTELAND,
|
||||
BEACH,
|
||||
NETHER,
|
||||
END,
|
||||
MUSHROOM,
|
||||
MAGICAL;
|
||||
}
|
||||
|
||||
private static final int BIOME_LIST_SIZE = 256;
|
||||
private static BiomeInfo[] biomeList = new BiomeInfo[BIOME_LIST_SIZE];
|
||||
private static ArrayList<BiomeGenBase>[] typeInfoList = new ArrayList[Type.values().length];
|
||||
|
||||
private static class BiomeInfo
|
||||
{
|
||||
public EnumSet<Type> typeList;
|
||||
|
||||
public BiomeInfo(Type[] types)
|
||||
{
|
||||
typeList = EnumSet.noneOf(Type.class);
|
||||
for(Type t : types)
|
||||
{
|
||||
typeList.add(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static
|
||||
{
|
||||
registerVanillaBiomes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a biome with a specific biome type
|
||||
*
|
||||
* @param biome the biome to be registered
|
||||
* @param type the type to register the biome as
|
||||
* @return returns true if the biome was registered successfully
|
||||
*/
|
||||
public static boolean registerBiomeType(BiomeGenBase biome, Type ... types)
|
||||
{
|
||||
if(BiomeGenBase.biomeList[biome.biomeID] != null)
|
||||
{
|
||||
for(Type type : types)
|
||||
{
|
||||
if(typeInfoList[type.ordinal()] == null)
|
||||
{
|
||||
typeInfoList[type.ordinal()] = new ArrayList<BiomeGenBase>();
|
||||
}
|
||||
|
||||
typeInfoList[type.ordinal()].add(biome);
|
||||
}
|
||||
|
||||
if(biomeList[biome.biomeID] == null)
|
||||
{
|
||||
biomeList[biome.biomeID] = new BiomeInfo(types);
|
||||
}
|
||||
else
|
||||
{
|
||||
for(Type type : types)
|
||||
{
|
||||
biomeList[biome.biomeID].typeList.add(type);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of biomes registered with a specific type
|
||||
*
|
||||
* @param type the Type to look for
|
||||
* @return a list of biomes of the specified type, null if there are none
|
||||
*/
|
||||
public static BiomeGenBase[] getBiomesForType(Type type)
|
||||
{
|
||||
if(typeInfoList[type.ordinal()] != null)
|
||||
{
|
||||
return (BiomeGenBase[])typeInfoList[type.ordinal()].toArray(new BiomeGenBase[0]);
|
||||
}
|
||||
|
||||
return new BiomeGenBase[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of Types that a specific biome is registered with
|
||||
*
|
||||
* @param biome the biome to check
|
||||
* @return the list of types, null if there are none
|
||||
*/
|
||||
public static Type[] getTypesForBiome(BiomeGenBase biome)
|
||||
{
|
||||
checkRegistration(biome);
|
||||
|
||||
if(biomeList[biome.biomeID] != null)
|
||||
{
|
||||
return (Type[])biomeList[biome.biomeID].typeList.toArray(new Type[0]);
|
||||
}
|
||||
|
||||
return new Type[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if two biomes are registered as having the same type
|
||||
*
|
||||
* @param biomeA
|
||||
* @param biomeB
|
||||
* @return returns true if a common type is found, false otherwise
|
||||
*/
|
||||
public static boolean areBiomesEquivalent(BiomeGenBase biomeA, BiomeGenBase biomeB)
|
||||
{
|
||||
int a = biomeA.biomeID;
|
||||
int b = biomeB.biomeID;
|
||||
|
||||
checkRegistration(biomeA);
|
||||
checkRegistration(biomeB);
|
||||
|
||||
if(biomeList[a] != null && biomeList[b] != null)
|
||||
{
|
||||
for(Type type : biomeList[a].typeList)
|
||||
{
|
||||
if(containsType(biomeList[b], type))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if the given biome is registered as being a specific type
|
||||
*
|
||||
* @param biome the biome to be considered
|
||||
* @param type the type to check for
|
||||
* @return returns true if the biome is registered as being of type type, false otherwise
|
||||
*/
|
||||
public static boolean isBiomeOfType(BiomeGenBase biome, Type type)
|
||||
{
|
||||
checkRegistration(biome);
|
||||
|
||||
if(biomeList[biome.biomeID] != null)
|
||||
{
|
||||
return containsType(biomeList[biome.biomeID], type);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks to see if the given biome has been registered as being of any type
|
||||
* @param biome the biome to consider
|
||||
* @return returns true if the biome has been registered, false otherwise
|
||||
*/
|
||||
public static boolean isBiomeRegistered(BiomeGenBase biome)
|
||||
{
|
||||
return biomeList[biome.biomeID] != null;
|
||||
}
|
||||
|
||||
public static boolean isBiomeRegistered(int biomeID)
|
||||
{
|
||||
return biomeList[biomeID] != null;
|
||||
}
|
||||
|
||||
public static void registerAllBiomes()
|
||||
{
|
||||
FMLLog.warning("Redundant call to BiomeDictionary.registerAllBiomes ignored");
|
||||
}
|
||||
/**
|
||||
* Loops through the biome list and automatically adds tags to any biome that does not have any
|
||||
* This is called by Forge at postinit time. It will additionally dispatch any deferred decorator
|
||||
* creation events.
|
||||
*
|
||||
* DO NOT call this during world generation
|
||||
*/
|
||||
public static void registerAllBiomesAndGenerateEvents()
|
||||
{
|
||||
for(int i = 0; i < BiomeGenBase.biomeList.length; i++)
|
||||
{
|
||||
BiomeGenBase biome = BiomeGenBase.biomeList[i];
|
||||
|
||||
if(biome == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (biome.theBiomeDecorator instanceof DeferredBiomeDecorator)
|
||||
{
|
||||
DeferredBiomeDecorator decorator = (DeferredBiomeDecorator) biome.theBiomeDecorator;
|
||||
decorator.fireCreateEventAndReplace();
|
||||
}
|
||||
|
||||
checkRegistration(biome);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically looks for and registers a given biome with appropriate tags
|
||||
* This method is called automatically if a biome has not been registered with any tags,
|
||||
* And another method requests information about it
|
||||
*
|
||||
* NOTE: You can opt out of having your biome registered by registering it as type NULL
|
||||
*
|
||||
* @param biome the biome to be considered
|
||||
*/
|
||||
public static void makeBestGuess(BiomeGenBase biome)
|
||||
{
|
||||
if(biome.theBiomeDecorator.treesPerChunk >= 3)
|
||||
{
|
||||
if(biome.isHighHumidity() && biome.temperature >= 1.0F)
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, JUNGLE);
|
||||
}
|
||||
else if(!biome.isHighHumidity())
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, FOREST);
|
||||
}
|
||||
}
|
||||
else if(biome.maxHeight <= 0.3F && biome.maxHeight >= 0.0F)
|
||||
{
|
||||
if(!biome.isHighHumidity() || biome.minHeight >= 0.0F)
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, PLAINS);
|
||||
}
|
||||
}
|
||||
|
||||
if(biome.isHighHumidity() && biome.minHeight < 0.0F && (biome.maxHeight <= 0.3F && biome.maxHeight >= 0.0F))
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, SWAMP);
|
||||
}
|
||||
|
||||
if(biome.minHeight <= -0.5F)
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, WATER);
|
||||
}
|
||||
|
||||
if(biome.maxHeight >= 1.5F)
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, MOUNTAIN);
|
||||
}
|
||||
|
||||
if(biome.getEnableSnow() || biome.temperature < 0.2F)
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, FROZEN);
|
||||
}
|
||||
|
||||
if(!biome.isHighHumidity() && biome.temperature >= 1.0F)
|
||||
{
|
||||
BiomeDictionary.registerBiomeType(biome, DESERT);
|
||||
}
|
||||
}
|
||||
|
||||
//Internal implementation
|
||||
private static void checkRegistration(BiomeGenBase biome)
|
||||
{
|
||||
if(!isBiomeRegistered(biome))
|
||||
{
|
||||
makeBestGuess(biome);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean containsType(BiomeInfo info, Type type)
|
||||
{
|
||||
return info.typeList.contains(type);
|
||||
}
|
||||
|
||||
private static void registerVanillaBiomes()
|
||||
{
|
||||
registerBiomeType(ocean, WATER );
|
||||
registerBiomeType(plains, PLAINS );
|
||||
registerBiomeType(desert, DESERT );
|
||||
registerBiomeType(extremeHills, MOUNTAIN );
|
||||
registerBiomeType(forest, FOREST );
|
||||
registerBiomeType(taiga, FOREST, FROZEN);
|
||||
registerBiomeType(taigaHills, FOREST, FROZEN);
|
||||
registerBiomeType(swampland, SWAMP );
|
||||
registerBiomeType(river, WATER );
|
||||
registerBiomeType(frozenOcean, WATER, FROZEN);
|
||||
registerBiomeType(frozenRiver, WATER, FROZEN);
|
||||
registerBiomeType(icePlains, FROZEN );
|
||||
registerBiomeType(iceMountains, FROZEN );
|
||||
registerBiomeType(beach, BEACH );
|
||||
registerBiomeType(desertHills, DESERT );
|
||||
registerBiomeType(jungle, JUNGLE );
|
||||
registerBiomeType(jungleHills, JUNGLE );
|
||||
registerBiomeType(forestHills, FOREST );
|
||||
registerBiomeType(sky, END );
|
||||
registerBiomeType(hell, NETHER );
|
||||
registerBiomeType(mushroomIsland, MUSHROOM );
|
||||
registerBiomeType(extremeHillsEdge, MOUNTAIN );
|
||||
registerBiomeType(mushroomIslandShore, MUSHROOM, BEACH);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import net.minecraft.world.biome.BiomeGenBase;
|
||||
import net.minecraft.world.gen.ChunkProviderGenerate;
|
||||
import net.minecraft.world.chunk.IChunkProvider;
|
||||
import net.minecraft.world.gen.structure.MapGenStronghold;
|
||||
import net.minecraft.world.gen.structure.MapGenVillage;
|
||||
import net.minecraft.world.biome.WorldChunkManager;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class BiomeManager
|
||||
{
|
||||
public static void addVillageBiome(BiomeGenBase biome, boolean canSpawn)
|
||||
{
|
||||
if (!MapGenVillage.villageSpawnBiomes.contains(biome))
|
||||
{
|
||||
ArrayList<BiomeGenBase> biomes = new ArrayList<BiomeGenBase>(MapGenVillage.villageSpawnBiomes);
|
||||
biomes.add(biome);
|
||||
MapGenVillage.villageSpawnBiomes = biomes;
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeVillageBiome(BiomeGenBase biome)
|
||||
{
|
||||
if (MapGenVillage.villageSpawnBiomes.contains(biome))
|
||||
{
|
||||
ArrayList<BiomeGenBase> biomes = new ArrayList<BiomeGenBase>(MapGenVillage.villageSpawnBiomes);
|
||||
biomes.remove(biome);
|
||||
MapGenVillage.villageSpawnBiomes = biomes;
|
||||
}
|
||||
}
|
||||
|
||||
public static void addStrongholdBiome(BiomeGenBase biome)
|
||||
{
|
||||
if (!MapGenStronghold.allowedBiomes.contains(biome))
|
||||
{
|
||||
MapGenStronghold.allowedBiomes.add(biome);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeStrongholdBiome(BiomeGenBase biome)
|
||||
{
|
||||
if (MapGenStronghold.allowedBiomes.contains(biome))
|
||||
{
|
||||
MapGenStronghold.allowedBiomes.remove(biome);
|
||||
}
|
||||
}
|
||||
|
||||
public static void addSpawnBiome(BiomeGenBase biome)
|
||||
{
|
||||
if (!WorldChunkManager.allowedBiomes.contains(biome))
|
||||
{
|
||||
WorldChunkManager.allowedBiomes.add(biome);
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeSpawnBiome(BiomeGenBase biome)
|
||||
{
|
||||
if (WorldChunkManager.allowedBiomes.contains(biome))
|
||||
{
|
||||
WorldChunkManager.allowedBiomes.remove(biome);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.WeightedRandom;
|
||||
import net.minecraft.util.WeightedRandomChestContent;
|
||||
import net.minecraft.world.WorldServer;
|
||||
import net.minecraft.world.gen.feature.WorldGenDungeons;
|
||||
import net.minecraft.world.gen.structure.*;
|
||||
import net.minecraftforge.oredict.OreDictionary;
|
||||
|
||||
public class ChestGenHooks
|
||||
{
|
||||
//Currently implemented categories for chests/dispensers, Dungeon loot is still in DungeonHooks
|
||||
public static final String MINESHAFT_CORRIDOR = "mineshaftCorridor";
|
||||
public static final String PYRAMID_DESERT_CHEST = "pyramidDesertyChest";
|
||||
public static final String PYRAMID_JUNGLE_CHEST = "pyramidJungleChest";
|
||||
public static final String PYRAMID_JUNGLE_DISPENSER = "pyramidJungleDispenser";
|
||||
public static final String STRONGHOLD_CORRIDOR = "strongholdCorridor";
|
||||
public static final String STRONGHOLD_LIBRARY = "strongholdLibrary";
|
||||
public static final String STRONGHOLD_CROSSING = "strongholdCrossing";
|
||||
public static final String VILLAGE_BLACKSMITH = "villageBlacksmith";
|
||||
public static final String BONUS_CHEST = "bonusChest";
|
||||
public static final String DUNGEON_CHEST = "dungeonChest";
|
||||
|
||||
private static final HashMap<String, ChestGenHooks> chestInfo = new HashMap<String, ChestGenHooks>();
|
||||
private static boolean hasInit = false;
|
||||
static
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
private static void init()
|
||||
{
|
||||
if (hasInit)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
hasInit = true;
|
||||
|
||||
addInfo(MINESHAFT_CORRIDOR, StructureMineshaftPieces.mineshaftChestContents, 3, 7);
|
||||
addInfo(PYRAMID_DESERT_CHEST, ComponentScatteredFeatureDesertPyramid.itemsToGenerateInTemple, 2, 7);
|
||||
addInfo(PYRAMID_JUNGLE_CHEST, ComponentScatteredFeatureJunglePyramid.junglePyramidsChestContents, 2, 7);
|
||||
addInfo(PYRAMID_JUNGLE_DISPENSER, ComponentScatteredFeatureJunglePyramid.junglePyramidsDispenserContents, 2, 2);
|
||||
addInfo(STRONGHOLD_CORRIDOR, ComponentStrongholdChestCorridor.strongholdChestContents, 2, 4);
|
||||
addInfo(STRONGHOLD_LIBRARY, ComponentStrongholdLibrary.strongholdLibraryChestContents, 1, 5);
|
||||
addInfo(STRONGHOLD_CROSSING, ComponentStrongholdRoomCrossing.strongholdRoomCrossingChestContents, 1, 5);
|
||||
addInfo(VILLAGE_BLACKSMITH, ComponentVillageHouse2.villageBlacksmithChestContents, 3, 9);
|
||||
addInfo(BONUS_CHEST, WorldServer.bonusChestContent, 10, 10);
|
||||
addInfo(DUNGEON_CHEST, WorldGenDungeons.field_111189_a, 8, 8);
|
||||
|
||||
ItemStack book = new ItemStack(Item.enchantedBook, 1, 0);
|
||||
WeightedRandomChestContent tmp = new WeightedRandomChestContent(book, 1, 1, 1);
|
||||
getInfo(MINESHAFT_CORRIDOR ).addItem(tmp);
|
||||
getInfo(PYRAMID_DESERT_CHEST).addItem(tmp);
|
||||
getInfo(PYRAMID_JUNGLE_CHEST).addItem(tmp);
|
||||
getInfo(STRONGHOLD_CORRIDOR ).addItem(tmp);
|
||||
getInfo(STRONGHOLD_LIBRARY ).addItem(new WeightedRandomChestContent(book, 1, 5, 2));
|
||||
getInfo(STRONGHOLD_CROSSING ).addItem(tmp);
|
||||
getInfo(DUNGEON_CHEST ).addItem(tmp);
|
||||
}
|
||||
|
||||
static void addDungeonLoot(ChestGenHooks dungeon, ItemStack item, int weight, int min, int max)
|
||||
{
|
||||
dungeon.addItem(new WeightedRandomChestContent(item, min, max, weight));
|
||||
}
|
||||
|
||||
private static void addInfo(String category, WeightedRandomChestContent[] items, int min, int max)
|
||||
{
|
||||
chestInfo.put(category, new ChestGenHooks(category, items, min, max));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves, or creates the info class for the specified category.
|
||||
*
|
||||
* @param category The category name
|
||||
* @return A instance of ChestGenHooks for the specified category.
|
||||
*/
|
||||
public static ChestGenHooks getInfo(String category)
|
||||
{
|
||||
if (!chestInfo.containsKey(category))
|
||||
{
|
||||
chestInfo.put(category, new ChestGenHooks(category));
|
||||
}
|
||||
return chestInfo.get(category);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an array of items based on the input min/max count.
|
||||
* If the stack can not hold the total amount, it will be split into
|
||||
* stacks of size 1.
|
||||
*
|
||||
* @param rand A random number generator
|
||||
* @param source Source item stack
|
||||
* @param min Minimum number of items
|
||||
* @param max Maximum number of items
|
||||
* @return An array containing the generated item stacks
|
||||
*/
|
||||
public static ItemStack[] generateStacks(Random rand, ItemStack source, int min, int max)
|
||||
{
|
||||
int count = min + (rand.nextInt(max - min + 1));
|
||||
|
||||
ItemStack[] ret;
|
||||
if (source.getItem() == null)
|
||||
{
|
||||
ret = new ItemStack[0];
|
||||
}
|
||||
else if (count > source.getMaxStackSize())
|
||||
{
|
||||
ret = new ItemStack[count];
|
||||
for (int x = 0; x < count; x++)
|
||||
{
|
||||
ret[x] = source.copy();
|
||||
ret[x].stackSize = 1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = new ItemStack[1];
|
||||
ret[0] = source.copy();
|
||||
ret[0].stackSize = count;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
//shortcut functions, See the non-static versions below
|
||||
public static WeightedRandomChestContent[] getItems(String category, Random rnd){ return getInfo(category).getItems(rnd); }
|
||||
public static int getCount(String category, Random rand){ return getInfo(category).getCount(rand); }
|
||||
public static void addItem(String category, WeightedRandomChestContent item){ getInfo(category).addItem(item); }
|
||||
public static void removeItem(String category, ItemStack item){ getInfo(category).removeItem(item); }
|
||||
public static ItemStack getOneItem(String category, Random rand){ return getInfo(category).getOneItem(rand); }
|
||||
|
||||
private String category;
|
||||
private int countMin = 0;
|
||||
private int countMax = 0;
|
||||
//TO-DO: Privatize this once again when we remove the Deprecated stuff in DungeonHooks
|
||||
ArrayList<WeightedRandomChestContent> contents = new ArrayList<WeightedRandomChestContent>();
|
||||
|
||||
public ChestGenHooks(String category)
|
||||
{
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public ChestGenHooks(String category, WeightedRandomChestContent[] items, int min, int max)
|
||||
{
|
||||
this(category);
|
||||
for (WeightedRandomChestContent item : items)
|
||||
{
|
||||
contents.add(item);
|
||||
}
|
||||
countMin = min;
|
||||
countMax = max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new entry into the possible items to generate.
|
||||
*
|
||||
* @param item The item to add.
|
||||
*/
|
||||
public void addItem(WeightedRandomChestContent item)
|
||||
{
|
||||
contents.add(item);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all items that match the input item stack, Only metadata and item ID are checked.
|
||||
* If the input item has a metadata of -1, all metadatas will match.
|
||||
*
|
||||
* @param item The item to check
|
||||
*/
|
||||
public void removeItem(ItemStack item)
|
||||
{
|
||||
Iterator<WeightedRandomChestContent> itr = contents.iterator();
|
||||
while(itr.hasNext())
|
||||
{
|
||||
WeightedRandomChestContent cont = itr.next();
|
||||
if (item.isItemEqual(cont.theItemId) || (item.getItemDamage() == OreDictionary.WILDCARD_VALUE && item.itemID == cont.theItemId.itemID))
|
||||
{
|
||||
itr.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an array of all random objects that are associated with this category.
|
||||
*
|
||||
* @return The random objects
|
||||
*/
|
||||
public WeightedRandomChestContent[] getItems(Random rnd)
|
||||
{
|
||||
ArrayList<WeightedRandomChestContent> ret = new ArrayList<WeightedRandomChestContent>();
|
||||
|
||||
for (WeightedRandomChestContent orig : contents)
|
||||
{
|
||||
Item item = orig.theItemId.getItem();
|
||||
|
||||
if (item != null)
|
||||
{
|
||||
WeightedRandomChestContent n = item.getChestGenBase(this, rnd, orig);
|
||||
if (n != null)
|
||||
{
|
||||
ret.add(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ret.toArray(new WeightedRandomChestContent[ret.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a random number between countMin and countMax.
|
||||
*
|
||||
* @param rand A RNG
|
||||
* @return A random number where countMin <= num <= countMax
|
||||
*/
|
||||
public int getCount(Random rand)
|
||||
{
|
||||
return countMin < countMax ? countMin + rand.nextInt(countMax - countMin) : countMin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a single ItemStack from the possible items in this registry,
|
||||
* Useful if you just want a quick and dirty random Item.
|
||||
*
|
||||
* @param rand A Random Number gen
|
||||
* @return A single ItemStack, or null if it could not get one.
|
||||
*/
|
||||
public ItemStack getOneItem(Random rand)
|
||||
{
|
||||
WeightedRandomChestContent[] items = getItems(rand);
|
||||
WeightedRandomChestContent item = (WeightedRandomChestContent)WeightedRandom.getRandomItem(rand, items);
|
||||
ItemStack[] stacks = ChestGenHooks.generateStacks(rand, item.theItemId, item.theMinimumChanceToGenerateItem, item.theMaximumChanceToGenerateItem);
|
||||
return (stacks.length > 0 ? stacks[0] : null);
|
||||
}
|
||||
|
||||
//Accessors
|
||||
public int getMin(){ return countMin; }
|
||||
public int getMax(){ return countMax; }
|
||||
public void setMin(int value){ countMin = value; }
|
||||
public void setMax(int value){ countMax = value; }
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import static net.minecraftforge.common.Configuration.NEW_LINE;
|
||||
import static net.minecraftforge.common.Configuration.allowedProperties;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
import com.google.common.base.Splitter;
|
||||
|
||||
public class ConfigCategory implements Map<String, Property>
|
||||
{
|
||||
private String name;
|
||||
private String comment;
|
||||
private ArrayList<ConfigCategory> children = new ArrayList<ConfigCategory>();
|
||||
private Map<String, Property> properties = new TreeMap<String, Property>();
|
||||
public final ConfigCategory parent;
|
||||
private boolean changed = false;
|
||||
|
||||
public ConfigCategory(String name)
|
||||
{
|
||||
this(name, null);
|
||||
}
|
||||
|
||||
public ConfigCategory(String name, ConfigCategory parent)
|
||||
{
|
||||
this.name = name;
|
||||
this.parent = parent;
|
||||
if (parent != null)
|
||||
{
|
||||
parent.children.add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean equals(Object obj)
|
||||
{
|
||||
if (obj instanceof ConfigCategory)
|
||||
{
|
||||
ConfigCategory cat = (ConfigCategory)obj;
|
||||
return name.equals(cat.name) && children.equals(cat.children);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public String getQualifiedName()
|
||||
{
|
||||
return getQualifiedName(name, parent);
|
||||
}
|
||||
|
||||
public static String getQualifiedName(String name, ConfigCategory parent)
|
||||
{
|
||||
return (parent == null ? name : parent.getQualifiedName() + Configuration.CATEGORY_SPLITTER + name);
|
||||
}
|
||||
|
||||
public ConfigCategory getFirstParent()
|
||||
{
|
||||
return (parent == null ? this : parent.getFirstParent());
|
||||
}
|
||||
|
||||
public boolean isChild()
|
||||
{
|
||||
return parent != null;
|
||||
}
|
||||
|
||||
public Map<String, Property> getValues()
|
||||
{
|
||||
return ImmutableMap.copyOf(properties);
|
||||
}
|
||||
|
||||
public void setComment(String comment)
|
||||
{
|
||||
this.comment = comment;
|
||||
}
|
||||
|
||||
public boolean containsKey(String key)
|
||||
{
|
||||
return properties.containsKey(key);
|
||||
}
|
||||
|
||||
public Property get(String key)
|
||||
{
|
||||
return properties.get(key);
|
||||
}
|
||||
|
||||
private void write(BufferedWriter out, String... data) throws IOException
|
||||
{
|
||||
write(out, true, data);
|
||||
}
|
||||
|
||||
private void write(BufferedWriter out, boolean new_line, String... data) throws IOException
|
||||
{
|
||||
for (int x = 0; x < data.length; x++)
|
||||
{
|
||||
out.write(data[x]);
|
||||
}
|
||||
if (new_line) out.write(NEW_LINE);
|
||||
}
|
||||
|
||||
public void write(BufferedWriter out, int indent) throws IOException
|
||||
{
|
||||
String pad0 = getIndent(indent);
|
||||
String pad1 = getIndent(indent + 1);
|
||||
String pad2 = getIndent(indent + 2);
|
||||
|
||||
write(out, pad0, "####################");
|
||||
write(out, pad0, "# ", name);
|
||||
|
||||
if (comment != null)
|
||||
{
|
||||
write(out, pad0, "#===================");
|
||||
Splitter splitter = Splitter.onPattern("\r?\n");
|
||||
|
||||
for (String line : splitter.split(comment))
|
||||
{
|
||||
write(out, pad0, "# ", line);
|
||||
}
|
||||
}
|
||||
|
||||
write(out, pad0, "####################", NEW_LINE);
|
||||
|
||||
if (!allowedProperties.matchesAllOf(name))
|
||||
{
|
||||
name = '"' + name + '"';
|
||||
}
|
||||
|
||||
write(out, pad0, name, " {");
|
||||
|
||||
Property[] props = properties.values().toArray(new Property[properties.size()]);
|
||||
|
||||
for (int x = 0; x < props.length; x++)
|
||||
{
|
||||
Property prop = props[x];
|
||||
|
||||
if (prop.comment != null)
|
||||
{
|
||||
if (x != 0)
|
||||
{
|
||||
out.newLine();
|
||||
}
|
||||
|
||||
Splitter splitter = Splitter.onPattern("\r?\n");
|
||||
for (String commentLine : splitter.split(prop.comment))
|
||||
{
|
||||
write(out, pad1, "# ", commentLine);
|
||||
}
|
||||
}
|
||||
|
||||
String propName = prop.getName();
|
||||
|
||||
if (!allowedProperties.matchesAllOf(propName))
|
||||
{
|
||||
propName = '"' + propName + '"';
|
||||
}
|
||||
|
||||
if (prop.isList())
|
||||
{
|
||||
char type = prop.getType().getID();
|
||||
|
||||
write(out, pad1, String.valueOf(type), ":", propName, " <");
|
||||
|
||||
for (String line : prop.getStringList())
|
||||
{
|
||||
write(out, pad2, line);
|
||||
}
|
||||
|
||||
write(out, pad1, " >");
|
||||
}
|
||||
else if (prop.getType() == null)
|
||||
{
|
||||
write(out, pad1, propName, "=", prop.getString());
|
||||
}
|
||||
else
|
||||
{
|
||||
char type = prop.getType().getID();
|
||||
write(out, pad1, String.valueOf(type), ":", propName, "=", prop.getString());
|
||||
}
|
||||
}
|
||||
|
||||
for (ConfigCategory child : children)
|
||||
{
|
||||
child.write(out, indent + 1);
|
||||
}
|
||||
|
||||
write(out, pad0, "}", NEW_LINE);
|
||||
}
|
||||
|
||||
private String getIndent(int indent)
|
||||
{
|
||||
StringBuilder buf = new StringBuilder("");
|
||||
for (int x = 0; x < indent; x++)
|
||||
{
|
||||
buf.append(" ");
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public boolean hasChanged()
|
||||
{
|
||||
if (changed) return true;
|
||||
for (Property prop : properties.values())
|
||||
{
|
||||
if (prop.hasChanged()) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void resetChangedState()
|
||||
{
|
||||
changed = false;
|
||||
for (Property prop : properties.values())
|
||||
{
|
||||
prop.resetChangedState();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//Map bouncer functions for compatibility with older mods, to be removed once all mods stop using it.
|
||||
@Override public int size(){ return properties.size(); }
|
||||
@Override public boolean isEmpty() { return properties.isEmpty(); }
|
||||
@Override public boolean containsKey(Object key) { return properties.containsKey(key); }
|
||||
@Override public boolean containsValue(Object value){ return properties.containsValue(value); }
|
||||
@Override public Property get(Object key) { return properties.get(key); }
|
||||
@Override public Property put(String key, Property value)
|
||||
{
|
||||
changed = true;
|
||||
return properties.put(key, value);
|
||||
}
|
||||
@Override public Property remove(Object key)
|
||||
{
|
||||
changed = true;
|
||||
return properties.remove(key);
|
||||
}
|
||||
@Override public void putAll(Map<? extends String, ? extends Property> m)
|
||||
{
|
||||
changed = true;
|
||||
properties.putAll(m);
|
||||
}
|
||||
@Override public void clear()
|
||||
{
|
||||
changed = true;
|
||||
properties.clear();
|
||||
}
|
||||
@Override public Set<String> keySet() { return properties.keySet(); }
|
||||
@Override public Collection<Property> values() { return properties.values(); }
|
||||
|
||||
@Override //Immutable copy, changes will NOT be reflected in this category
|
||||
public Set<java.util.Map.Entry<String, Property>> entrySet()
|
||||
{
|
||||
return ImmutableSet.copyOf(properties.entrySet());
|
||||
}
|
||||
|
||||
public Set<ConfigCategory> getChildren(){ return ImmutableSet.copyOf(children); }
|
||||
|
||||
public void removeChild(ConfigCategory child)
|
||||
{
|
||||
if (children.contains(child))
|
||||
{
|
||||
children.remove(child);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,927 @@
|
||||
/**
|
||||
* This software is provided under the terms of the Minecraft Forge Public
|
||||
* License v1.0.
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import static net.minecraftforge.common.Property.Type.BOOLEAN;
|
||||
import static net.minecraftforge.common.Property.Type.DOUBLE;
|
||||
import static net.minecraftforge.common.Property.Type.INTEGER;
|
||||
import static net.minecraftforge.common.Property.Type.STRING;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PushbackInputStream;
|
||||
import java.io.Reader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.item.Item;
|
||||
|
||||
import com.google.common.base.CharMatcher;
|
||||
import com.google.common.collect.ImmutableSet;
|
||||
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
import cpw.mods.fml.common.Loader;
|
||||
import cpw.mods.fml.relauncher.FMLInjectionData;
|
||||
|
||||
/**
|
||||
* This class offers advanced configurations capabilities, allowing to provide
|
||||
* various categories for configuration variables.
|
||||
*/
|
||||
public class Configuration
|
||||
{
|
||||
private static boolean[] configMarkers = new boolean[Item.itemsList.length];
|
||||
private static final int ITEM_SHIFT = 256;
|
||||
private static final int MAX_BLOCKS = 4096;
|
||||
|
||||
public static final String CATEGORY_GENERAL = "general";
|
||||
public static final String CATEGORY_BLOCK = "block";
|
||||
public static final String CATEGORY_ITEM = "item";
|
||||
public static final String ALLOWED_CHARS = "._-";
|
||||
public static final String DEFAULT_ENCODING = "UTF-8";
|
||||
public static final String CATEGORY_SPLITTER = ".";
|
||||
public static final String NEW_LINE;
|
||||
private static final Pattern CONFIG_START = Pattern.compile("START: \"([^\\\"]+)\"");
|
||||
private static final Pattern CONFIG_END = Pattern.compile("END: \"([^\\\"]+)\"");
|
||||
public static final CharMatcher allowedProperties = CharMatcher.JAVA_LETTER_OR_DIGIT.or(CharMatcher.anyOf(ALLOWED_CHARS));
|
||||
private static Configuration PARENT = null;
|
||||
|
||||
File file;
|
||||
|
||||
private Map<String, ConfigCategory> categories = new TreeMap<String, ConfigCategory>();
|
||||
private Map<String, Configuration> children = new TreeMap<String, Configuration>();
|
||||
|
||||
private boolean caseSensitiveCustomCategories;
|
||||
public String defaultEncoding = DEFAULT_ENCODING;
|
||||
private String fileName = null;
|
||||
public boolean isChild = false;
|
||||
private boolean changed = false;
|
||||
|
||||
static
|
||||
{
|
||||
Arrays.fill(configMarkers, false);
|
||||
NEW_LINE = System.getProperty("line.separator");
|
||||
}
|
||||
|
||||
public Configuration(){}
|
||||
|
||||
/**
|
||||
* Create a configuration file for the file given in parameter.
|
||||
*/
|
||||
public Configuration(File file)
|
||||
{
|
||||
this.file = file;
|
||||
String basePath = ((File)(FMLInjectionData.data()[6])).getAbsolutePath().replace(File.separatorChar, '/').replace("/.", "");
|
||||
String path = file.getAbsolutePath().replace(File.separatorChar, '/').replace("/./", "/").replace(basePath, "");
|
||||
if (PARENT != null)
|
||||
{
|
||||
PARENT.setChild(path, this);
|
||||
isChild = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
fileName = path;
|
||||
load();
|
||||
}
|
||||
}
|
||||
|
||||
public Configuration(File file, boolean caseSensitiveCustomCategories)
|
||||
{
|
||||
this(file);
|
||||
this.caseSensitiveCustomCategories = caseSensitiveCustomCategories;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or create a block id property. If the block id property key is
|
||||
* already in the configuration, then it will be used. Otherwise,
|
||||
* defaultId will be used, except if already taken, in which case this
|
||||
* will try to determine a free default id.
|
||||
*/
|
||||
public Property getBlock(String key, int defaultID) { return getBlock(CATEGORY_BLOCK, key, defaultID, null); }
|
||||
public Property getBlock(String key, int defaultID, String comment) { return getBlock(CATEGORY_BLOCK, key, defaultID, comment); }
|
||||
public Property getBlock(String category, String key, int defaultID) { return getBlockInternal(category, key, defaultID, null, 256, Block.blocksList.length); }
|
||||
public Property getBlock(String category, String key, int defaultID, String comment) { return getBlockInternal(category, key, defaultID, comment, 256, Block.blocksList.length); }
|
||||
|
||||
/**
|
||||
* Special version of getBlock to be used when you want to garentee the ID you get is below 256
|
||||
* This should ONLY be used by mods who do low level terrain generation, or ones that add new
|
||||
* biomes.
|
||||
* EXA: ExtraBiomesXL
|
||||
*
|
||||
* Specifically, if your block is used BEFORE the Chunk is created, and placed in the terrain byte array directly.
|
||||
* If you add a new biome and you set the top/filler block, they need to be <256, nothing else.
|
||||
*
|
||||
* If you're adding a new ore, DON'T call this function.
|
||||
*
|
||||
* Normal mods such as '50 new ores' do not need to be below 256 so should use the normal getBlock
|
||||
*/
|
||||
public Property getTerrainBlock(String category, String key, int defaultID, String comment)
|
||||
{
|
||||
return getBlockInternal(category, key, defaultID, comment, 0, 256);
|
||||
}
|
||||
|
||||
private Property getBlockInternal(String category, String key, int defaultID, String comment, int lower, int upper)
|
||||
{
|
||||
Property prop = get(category, key, -1, comment);
|
||||
|
||||
if (prop.getInt() != -1)
|
||||
{
|
||||
configMarkers[prop.getInt()] = true;
|
||||
return prop;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (defaultID < lower)
|
||||
{
|
||||
FMLLog.warning(
|
||||
"Mod attempted to get a block ID with a default in the Terrain Generation section, " +
|
||||
"mod authors should make sure there defaults are above 256 unless explicitly needed " +
|
||||
"for terrain generation. Most ores do not need to be below 256.");
|
||||
FMLLog.warning("Config \"%s\" Category: \"%s\" Key: \"%s\" Default: %d", fileName, category, key, defaultID);
|
||||
defaultID = upper - 1;
|
||||
}
|
||||
|
||||
if (Block.blocksList[defaultID] == null && !configMarkers[defaultID])
|
||||
{
|
||||
prop.set(defaultID);
|
||||
configMarkers[defaultID] = true;
|
||||
return prop;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int j = upper - 1; j > 0; j--)
|
||||
{
|
||||
if (Block.blocksList[j] == null && !configMarkers[j])
|
||||
{
|
||||
prop.set(j);
|
||||
configMarkers[j] = true;
|
||||
return prop;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException("No more block ids available for " + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Property getItem(String key, int defaultID) { return getItem(CATEGORY_ITEM, key, defaultID, null); }
|
||||
public Property getItem(String key, int defaultID, String comment) { return getItem(CATEGORY_ITEM, key, defaultID, comment); }
|
||||
public Property getItem(String category, String key, int defaultID) { return getItem(category, key, defaultID, null); }
|
||||
|
||||
public Property getItem(String category, String key, int defaultID, String comment)
|
||||
{
|
||||
Property prop = get(category, key, -1, comment);
|
||||
int defaultShift = defaultID + ITEM_SHIFT;
|
||||
|
||||
if (prop.getInt() != -1)
|
||||
{
|
||||
configMarkers[prop.getInt() + ITEM_SHIFT] = true;
|
||||
return prop;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (defaultID < MAX_BLOCKS - ITEM_SHIFT)
|
||||
{
|
||||
FMLLog.warning(
|
||||
"Mod attempted to get a item ID with a default value in the block ID section, " +
|
||||
"mod authors should make sure there defaults are above %d unless explicitly needed " +
|
||||
"so that all block ids are free to store blocks.", MAX_BLOCKS - ITEM_SHIFT);
|
||||
FMLLog.warning("Config \"%s\" Category: \"%s\" Key: \"%s\" Default: %d", fileName, category, key, defaultID);
|
||||
}
|
||||
|
||||
if (Item.itemsList[defaultShift] == null && !configMarkers[defaultShift] && defaultShift >= Block.blocksList.length)
|
||||
{
|
||||
prop.set(defaultID);
|
||||
configMarkers[defaultShift] = true;
|
||||
return prop;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int x = Item.itemsList.length - 1; x >= ITEM_SHIFT; x--)
|
||||
{
|
||||
if (Item.itemsList[x] == null && !configMarkers[x])
|
||||
{
|
||||
prop.set(x - ITEM_SHIFT);
|
||||
configMarkers[x] = true;
|
||||
return prop;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException("No more item ids available for " + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Property get(String category, String key, int defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, int defaultValue, String comment)
|
||||
{
|
||||
Property prop = get(category, key, Integer.toString(defaultValue), comment, INTEGER);
|
||||
if (!prop.isIntValue())
|
||||
{
|
||||
prop.set(defaultValue);
|
||||
}
|
||||
return prop;
|
||||
}
|
||||
|
||||
public Property get(String category, String key, boolean defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, boolean defaultValue, String comment)
|
||||
{
|
||||
Property prop = get(category, key, Boolean.toString(defaultValue), comment, BOOLEAN);
|
||||
if (!prop.isBooleanValue())
|
||||
{
|
||||
prop.set(defaultValue);
|
||||
}
|
||||
return prop;
|
||||
}
|
||||
|
||||
public Property get(String category, String key, double defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, double defaultValue, String comment)
|
||||
{
|
||||
Property prop = get(category, key, Double.toString(defaultValue), comment, DOUBLE);
|
||||
if (!prop.isDoubleValue())
|
||||
{
|
||||
prop.set(defaultValue);
|
||||
}
|
||||
return prop;
|
||||
}
|
||||
|
||||
public Property get(String category, String key, String defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, String defaultValue, String comment)
|
||||
{
|
||||
return get(category, key, defaultValue, comment, STRING);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, String[] defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, String[] defaultValue, String comment)
|
||||
{
|
||||
return get(category, key, defaultValue, comment, STRING);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, int[] defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, int[] defaultValue, String comment)
|
||||
{
|
||||
String[] values = new String[defaultValue.length];
|
||||
for (int i = 0; i < defaultValue.length; i++)
|
||||
{
|
||||
values[i] = Integer.toString(defaultValue[i]);
|
||||
}
|
||||
|
||||
Property prop = get(category, key, values, comment, INTEGER);
|
||||
if (!prop.isIntList())
|
||||
{
|
||||
prop.set(values);
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
public Property get(String category, String key, double[] defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, double[] defaultValue, String comment)
|
||||
{
|
||||
String[] values = new String[defaultValue.length];
|
||||
for (int i = 0; i < defaultValue.length; i++)
|
||||
{
|
||||
values[i] = Double.toString(defaultValue[i]);
|
||||
}
|
||||
|
||||
Property prop = get(category, key, values, comment, DOUBLE);
|
||||
|
||||
if (!prop.isDoubleList())
|
||||
{
|
||||
prop.set(values);
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
public Property get(String category, String key, boolean[] defaultValue)
|
||||
{
|
||||
return get(category, key, defaultValue, null);
|
||||
}
|
||||
|
||||
public Property get(String category, String key, boolean[] defaultValue, String comment)
|
||||
{
|
||||
String[] values = new String[defaultValue.length];
|
||||
for (int i = 0; i < defaultValue.length; i++)
|
||||
{
|
||||
values[i] = Boolean.toString(defaultValue[i]);
|
||||
}
|
||||
|
||||
Property prop = get(category, key, values, comment, BOOLEAN);
|
||||
|
||||
if (!prop.isBooleanList())
|
||||
{
|
||||
prop.set(values);
|
||||
}
|
||||
|
||||
return prop;
|
||||
}
|
||||
|
||||
public Property get(String category, String key, String defaultValue, String comment, Property.Type type)
|
||||
{
|
||||
if (!caseSensitiveCustomCategories)
|
||||
{
|
||||
category = category.toLowerCase(Locale.ENGLISH);
|
||||
}
|
||||
|
||||
ConfigCategory cat = getCategory(category);
|
||||
|
||||
if (cat.containsKey(key))
|
||||
{
|
||||
Property prop = cat.get(key);
|
||||
|
||||
if (prop.getType() == null)
|
||||
{
|
||||
prop = new Property(prop.getName(), prop.getString(), type);
|
||||
cat.put(key, prop);
|
||||
}
|
||||
|
||||
prop.comment = comment;
|
||||
return prop;
|
||||
}
|
||||
else if (defaultValue != null)
|
||||
{
|
||||
Property prop = new Property(key, defaultValue, type);
|
||||
prop.set(defaultValue); //Set and mark as dirty to signify it should save
|
||||
cat.put(key, prop);
|
||||
prop.comment = comment;
|
||||
return prop;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public Property get(String category, String key, String[] defaultValue, String comment, Property.Type type)
|
||||
{
|
||||
if (!caseSensitiveCustomCategories)
|
||||
{
|
||||
category = category.toLowerCase(Locale.ENGLISH);
|
||||
}
|
||||
|
||||
ConfigCategory cat = getCategory(category);
|
||||
|
||||
if (cat.containsKey(key))
|
||||
{
|
||||
Property prop = cat.get(key);
|
||||
|
||||
if (prop.getType() == null)
|
||||
{
|
||||
prop = new Property(prop.getName(), prop.getString(), type);
|
||||
cat.put(key, prop);
|
||||
}
|
||||
|
||||
prop.comment = comment;
|
||||
|
||||
return prop;
|
||||
}
|
||||
else if (defaultValue != null)
|
||||
{
|
||||
Property prop = new Property(key, defaultValue, type);
|
||||
prop.comment = comment;
|
||||
cat.put(key, prop);
|
||||
return prop;
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasCategory(String category)
|
||||
{
|
||||
return categories.get(category) != null;
|
||||
}
|
||||
|
||||
public boolean hasKey(String category, String key)
|
||||
{
|
||||
ConfigCategory cat = categories.get(category);
|
||||
return cat != null && cat.containsKey(key);
|
||||
}
|
||||
|
||||
public void load()
|
||||
{
|
||||
if (PARENT != null && PARENT != this)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
BufferedReader buffer = null;
|
||||
UnicodeInputStreamReader input = null;
|
||||
try
|
||||
{
|
||||
if (file.getParentFile() != null)
|
||||
{
|
||||
file.getParentFile().mkdirs();
|
||||
}
|
||||
|
||||
if (!file.exists() && !file.createNewFile())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.canRead())
|
||||
{
|
||||
input = new UnicodeInputStreamReader(new FileInputStream(file), defaultEncoding);
|
||||
defaultEncoding = input.getEncoding();
|
||||
buffer = new BufferedReader(input);
|
||||
|
||||
String line;
|
||||
ConfigCategory currentCat = null;
|
||||
Property.Type type = null;
|
||||
ArrayList<String> tmpList = null;
|
||||
int lineNum = 0;
|
||||
String name = null;
|
||||
|
||||
while (true)
|
||||
{
|
||||
lineNum++;
|
||||
line = buffer.readLine();
|
||||
|
||||
if (line == null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Matcher start = CONFIG_START.matcher(line);
|
||||
Matcher end = CONFIG_END.matcher(line);
|
||||
|
||||
if (start.matches())
|
||||
{
|
||||
fileName = start.group(1);
|
||||
categories = new TreeMap<String, ConfigCategory>();
|
||||
continue;
|
||||
}
|
||||
else if (end.matches())
|
||||
{
|
||||
fileName = end.group(1);
|
||||
Configuration child = new Configuration();
|
||||
child.categories = categories;
|
||||
this.children.put(fileName, child);
|
||||
continue;
|
||||
}
|
||||
|
||||
int nameStart = -1, nameEnd = -1;
|
||||
boolean skip = false;
|
||||
boolean quoted = false;
|
||||
|
||||
for (int i = 0; i < line.length() && !skip; ++i)
|
||||
{
|
||||
if (Character.isLetterOrDigit(line.charAt(i)) || ALLOWED_CHARS.indexOf(line.charAt(i)) != -1 || (quoted && line.charAt(i) != '"'))
|
||||
{
|
||||
if (nameStart == -1)
|
||||
{
|
||||
nameStart = i;
|
||||
}
|
||||
|
||||
nameEnd = i;
|
||||
}
|
||||
else if (Character.isWhitespace(line.charAt(i)))
|
||||
{
|
||||
// ignore space charaters
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (line.charAt(i))
|
||||
{
|
||||
case '#':
|
||||
skip = true;
|
||||
continue;
|
||||
|
||||
case '"':
|
||||
if (quoted)
|
||||
{
|
||||
quoted = false;
|
||||
}
|
||||
if (!quoted && nameStart == -1)
|
||||
{
|
||||
quoted = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case '{':
|
||||
name = line.substring(nameStart, nameEnd + 1);
|
||||
String qualifiedName = ConfigCategory.getQualifiedName(name, currentCat);
|
||||
|
||||
ConfigCategory cat = categories.get(qualifiedName);
|
||||
if (cat == null)
|
||||
{
|
||||
currentCat = new ConfigCategory(name, currentCat);
|
||||
categories.put(qualifiedName, currentCat);
|
||||
}
|
||||
else
|
||||
{
|
||||
currentCat = cat;
|
||||
}
|
||||
name = null;
|
||||
|
||||
break;
|
||||
|
||||
case '}':
|
||||
if (currentCat == null)
|
||||
{
|
||||
throw new RuntimeException(String.format("Config file corrupt, attepted to close to many categories '%s:%d'", fileName, lineNum));
|
||||
}
|
||||
currentCat = currentCat.parent;
|
||||
break;
|
||||
|
||||
case '=':
|
||||
name = line.substring(nameStart, nameEnd + 1);
|
||||
|
||||
if (currentCat == null)
|
||||
{
|
||||
throw new RuntimeException(String.format("'%s' has no scope in '%s:%d'", name, fileName, lineNum));
|
||||
}
|
||||
|
||||
Property prop = new Property(name, line.substring(i + 1), type, true);
|
||||
i = line.length();
|
||||
|
||||
currentCat.put(name, prop);
|
||||
|
||||
break;
|
||||
|
||||
case ':':
|
||||
type = Property.Type.tryParse(line.substring(nameStart, nameEnd + 1).charAt(0));
|
||||
nameStart = nameEnd = -1;
|
||||
break;
|
||||
|
||||
case '<':
|
||||
if (tmpList != null)
|
||||
{
|
||||
throw new RuntimeException(String.format("Malformed list property \"%s:%d\"", fileName, lineNum));
|
||||
}
|
||||
|
||||
name = line.substring(nameStart, nameEnd + 1);
|
||||
|
||||
if (currentCat == null)
|
||||
{
|
||||
throw new RuntimeException(String.format("'%s' has no scope in '%s:%d'", name, fileName, lineNum));
|
||||
}
|
||||
|
||||
tmpList = new ArrayList<String>();
|
||||
|
||||
skip = true;
|
||||
|
||||
break;
|
||||
|
||||
case '>':
|
||||
if (tmpList == null)
|
||||
{
|
||||
throw new RuntimeException(String.format("Malformed list property \"%s:%d\"", fileName, lineNum));
|
||||
}
|
||||
|
||||
currentCat.put(name, new Property(name, tmpList.toArray(new String[tmpList.size()]), type));
|
||||
name = null;
|
||||
tmpList = null;
|
||||
type = null;
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new RuntimeException(String.format("Unknown character '%s' in '%s:%d'", line.charAt(i), fileName, lineNum));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (quoted)
|
||||
{
|
||||
throw new RuntimeException(String.format("Unmatched quote in '%s:%d'", fileName, lineNum));
|
||||
}
|
||||
else if (tmpList != null && !skip)
|
||||
{
|
||||
tmpList.add(line.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (buffer != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
buffer.close();
|
||||
} catch (IOException e){}
|
||||
}
|
||||
if (input != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
input.close();
|
||||
} catch (IOException e){}
|
||||
}
|
||||
}
|
||||
|
||||
resetChangedState();
|
||||
}
|
||||
|
||||
public void save()
|
||||
{
|
||||
if (PARENT != null && PARENT != this)
|
||||
{
|
||||
PARENT.save();
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (file.getParentFile() != null)
|
||||
{
|
||||
file.getParentFile().mkdirs();
|
||||
}
|
||||
|
||||
if (!file.exists() && !file.createNewFile())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.canWrite())
|
||||
{
|
||||
FileOutputStream fos = new FileOutputStream(file);
|
||||
BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(fos, defaultEncoding));
|
||||
|
||||
buffer.write("# Configuration file" + NEW_LINE + NEW_LINE);
|
||||
|
||||
if (children.isEmpty())
|
||||
{
|
||||
save(buffer);
|
||||
}
|
||||
else
|
||||
{
|
||||
for (Map.Entry<String, Configuration> entry : children.entrySet())
|
||||
{
|
||||
buffer.write("START: \"" + entry.getKey() + "\"" + NEW_LINE);
|
||||
entry.getValue().save(buffer);
|
||||
buffer.write("END: \"" + entry.getKey() + "\"" + NEW_LINE + NEW_LINE);
|
||||
}
|
||||
}
|
||||
|
||||
buffer.close();
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void save(BufferedWriter out) throws IOException
|
||||
{
|
||||
for (ConfigCategory cat : categories.values())
|
||||
{
|
||||
if (!cat.isChild())
|
||||
{
|
||||
cat.write(out, 0);
|
||||
out.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public ConfigCategory getCategory(String category)
|
||||
{
|
||||
ConfigCategory ret = categories.get(category);
|
||||
|
||||
if (ret == null)
|
||||
{
|
||||
if (category.contains(CATEGORY_SPLITTER))
|
||||
{
|
||||
String[] hierarchy = category.split("\\"+CATEGORY_SPLITTER);
|
||||
ConfigCategory parent = categories.get(hierarchy[0]);
|
||||
|
||||
if (parent == null)
|
||||
{
|
||||
parent = new ConfigCategory(hierarchy[0]);
|
||||
categories.put(parent.getQualifiedName(), parent);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
for (int i = 1; i < hierarchy.length; i++)
|
||||
{
|
||||
String name = ConfigCategory.getQualifiedName(hierarchy[i], parent);
|
||||
ConfigCategory child = categories.get(name);
|
||||
|
||||
if (child == null)
|
||||
{
|
||||
child = new ConfigCategory(hierarchy[i], parent);
|
||||
categories.put(name, child);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
ret = child;
|
||||
parent = child;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = new ConfigCategory(category);
|
||||
categories.put(category, ret);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void removeCategory(ConfigCategory category)
|
||||
{
|
||||
for (ConfigCategory child : category.getChildren())
|
||||
{
|
||||
removeCategory(child);
|
||||
}
|
||||
|
||||
if (categories.containsKey(category.getQualifiedName()))
|
||||
{
|
||||
categories.remove(category.getQualifiedName());
|
||||
if (category.parent != null)
|
||||
{
|
||||
category.parent.removeChild(category);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void addCustomCategoryComment(String category, String comment)
|
||||
{
|
||||
if (!caseSensitiveCustomCategories)
|
||||
category = category.toLowerCase(Locale.ENGLISH);
|
||||
getCategory(category).setComment(comment);
|
||||
}
|
||||
|
||||
private void setChild(String name, Configuration child)
|
||||
{
|
||||
if (!children.containsKey(name))
|
||||
{
|
||||
children.put(name, child);
|
||||
changed = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Configuration old = children.get(name);
|
||||
child.categories = old.categories;
|
||||
child.fileName = old.fileName;
|
||||
old.changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
public static void enableGlobalConfig()
|
||||
{
|
||||
PARENT = new Configuration(new File(Loader.instance().getConfigDir(), "global.cfg"));
|
||||
PARENT.load();
|
||||
}
|
||||
|
||||
public static class UnicodeInputStreamReader extends Reader
|
||||
{
|
||||
private final InputStreamReader input;
|
||||
private final String defaultEnc;
|
||||
|
||||
public UnicodeInputStreamReader(InputStream source, String encoding) throws IOException
|
||||
{
|
||||
defaultEnc = encoding;
|
||||
String enc = encoding;
|
||||
byte[] data = new byte[4];
|
||||
|
||||
PushbackInputStream pbStream = new PushbackInputStream(source, data.length);
|
||||
int read = pbStream.read(data, 0, data.length);
|
||||
int size = 0;
|
||||
|
||||
int bom16 = (data[0] & 0xFF) << 8 | (data[1] & 0xFF);
|
||||
int bom24 = bom16 << 8 | (data[2] & 0xFF);
|
||||
int bom32 = bom24 << 8 | (data[3] & 0xFF);
|
||||
|
||||
if (bom24 == 0xEFBBBF)
|
||||
{
|
||||
enc = "UTF-8";
|
||||
size = 3;
|
||||
}
|
||||
else if (bom16 == 0xFEFF)
|
||||
{
|
||||
enc = "UTF-16BE";
|
||||
size = 2;
|
||||
}
|
||||
else if (bom16 == 0xFFFE)
|
||||
{
|
||||
enc = "UTF-16LE";
|
||||
size = 2;
|
||||
}
|
||||
else if (bom32 == 0x0000FEFF)
|
||||
{
|
||||
enc = "UTF-32BE";
|
||||
size = 4;
|
||||
}
|
||||
else if (bom32 == 0xFFFE0000) //This will never happen as it'll be caught by UTF-16LE,
|
||||
{ //but if anyone ever runs across a 32LE file, i'd like to disect it.
|
||||
enc = "UTF-32LE";
|
||||
size = 4;
|
||||
}
|
||||
|
||||
if (size < read)
|
||||
{
|
||||
pbStream.unread(data, size, read - size);
|
||||
}
|
||||
|
||||
this.input = new InputStreamReader(pbStream, enc);
|
||||
}
|
||||
|
||||
public String getEncoding()
|
||||
{
|
||||
return input.getEncoding();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(char[] cbuf, int off, int len) throws IOException
|
||||
{
|
||||
return input.read(cbuf, off, len);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException
|
||||
{
|
||||
input.close();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasChanged()
|
||||
{
|
||||
if (changed) return true;
|
||||
|
||||
for (ConfigCategory cat : categories.values())
|
||||
{
|
||||
if (cat.hasChanged()) return true;
|
||||
}
|
||||
|
||||
for (Configuration child : children.values())
|
||||
{
|
||||
if (child.hasChanged()) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void resetChangedState()
|
||||
{
|
||||
changed = false;
|
||||
for (ConfigCategory cat : categories.values())
|
||||
{
|
||||
cat.resetChangedState();
|
||||
}
|
||||
|
||||
for (Configuration child : children.values())
|
||||
{
|
||||
child.resetChangedState();
|
||||
}
|
||||
}
|
||||
|
||||
public Set<String> getCategoryNames()
|
||||
{
|
||||
return ImmutableSet.copyOf(categories.keySet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.BitSet;
|
||||
import java.util.HashSet;
|
||||
import java.util.Hashtable;
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.HashMultiset;
|
||||
import com.google.common.collect.ImmutableListMultimap;
|
||||
import com.google.common.collect.ListMultimap;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.MapMaker;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Multiset;
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
import cpw.mods.fml.common.FMLCommonHandler;
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.ChunkCoordIntPair;
|
||||
import net.minecraft.world.MinecraftException;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.WorldManager;
|
||||
import net.minecraft.world.WorldProvider;
|
||||
import net.minecraft.world.WorldProviderEnd;
|
||||
import net.minecraft.world.WorldProviderHell;
|
||||
import net.minecraft.world.WorldProviderSurface;
|
||||
import net.minecraft.world.WorldServer;
|
||||
import net.minecraft.world.WorldServerMulti;
|
||||
import net.minecraft.world.WorldSettings;
|
||||
import net.minecraft.world.storage.ISaveHandler;
|
||||
import net.minecraft.world.storage.SaveHandler;
|
||||
import net.minecraftforge.event.world.WorldEvent;
|
||||
|
||||
public class DimensionManager
|
||||
{
|
||||
private static Hashtable<Integer, Class<? extends WorldProvider>> providers = new Hashtable<Integer, Class<? extends WorldProvider>>();
|
||||
private static Hashtable<Integer, Boolean> spawnSettings = new Hashtable<Integer, Boolean>();
|
||||
private static Hashtable<Integer, WorldServer> worlds = new Hashtable<Integer, WorldServer>();
|
||||
private static boolean hasInit = false;
|
||||
private static Hashtable<Integer, Integer> dimensions = new Hashtable<Integer, Integer>();
|
||||
private static ArrayList<Integer> unloadQueue = new ArrayList<Integer>();
|
||||
private static BitSet dimensionMap = new BitSet(Long.SIZE << 4);
|
||||
private static ConcurrentMap<World, World> weakWorldMap = new MapMaker().weakKeys().weakValues().<World,World>makeMap();
|
||||
private static Multiset<Integer> leakedWorlds = HashMultiset.create();
|
||||
|
||||
public static boolean registerProviderType(int id, Class<? extends WorldProvider> provider, boolean keepLoaded)
|
||||
{
|
||||
if (providers.containsKey(id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
providers.put(id, provider);
|
||||
spawnSettings.put(id, keepLoaded);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters a Provider type, and returns a array of all dimensions that are
|
||||
* registered to this provider type.
|
||||
* If the return size is greater then 0, it is required that the caller either
|
||||
* change those dimensions's registered type, or replace this type before the
|
||||
* world is attempted to load, else the loader will throw an exception.
|
||||
*
|
||||
* @param id The provider type ID to unreigster
|
||||
* @return An array containing all dimension IDs still registered to this provider type.
|
||||
*/
|
||||
public static int[] unregisterProviderType(int id)
|
||||
{
|
||||
if (!providers.containsKey(id))
|
||||
{
|
||||
return new int[0];
|
||||
}
|
||||
providers.remove(id);
|
||||
spawnSettings.remove(id);
|
||||
|
||||
int[] ret = new int[dimensions.size()];
|
||||
int x = 0;
|
||||
for (Map.Entry<Integer, Integer> ent : dimensions.entrySet())
|
||||
{
|
||||
if (ent.getValue() == id)
|
||||
{
|
||||
ret[x++] = ent.getKey();
|
||||
}
|
||||
}
|
||||
|
||||
return Arrays.copyOf(ret, x);
|
||||
}
|
||||
|
||||
public static void init()
|
||||
{
|
||||
if (hasInit)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
hasInit = true;
|
||||
|
||||
registerProviderType( 0, WorldProviderSurface.class, true);
|
||||
registerProviderType(-1, WorldProviderHell.class, true);
|
||||
registerProviderType( 1, WorldProviderEnd.class, false);
|
||||
registerDimension( 0, 0);
|
||||
registerDimension(-1, -1);
|
||||
registerDimension( 1, 1);
|
||||
}
|
||||
|
||||
public static void registerDimension(int id, int providerType)
|
||||
{
|
||||
if (!providers.containsKey(providerType))
|
||||
{
|
||||
throw new IllegalArgumentException(String.format("Failed to register dimension for id %d, provider type %d does not exist", id, providerType));
|
||||
}
|
||||
if (dimensions.containsKey(id))
|
||||
{
|
||||
throw new IllegalArgumentException(String.format("Failed to register dimension for id %d, One is already registered", id));
|
||||
}
|
||||
dimensions.put(id, providerType);
|
||||
if (id >= 0)
|
||||
{
|
||||
dimensionMap.set(id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* For unregistering a dimension when the save is changed (disconnected from a server or loaded a new save
|
||||
*/
|
||||
public static void unregisterDimension(int id)
|
||||
{
|
||||
if (!dimensions.containsKey(id))
|
||||
{
|
||||
throw new IllegalArgumentException(String.format("Failed to unregister dimension for id %d; No provider registered", id));
|
||||
}
|
||||
dimensions.remove(id);
|
||||
}
|
||||
|
||||
public static boolean isDimensionRegistered(int dim)
|
||||
{
|
||||
return dimensions.containsKey(dim);
|
||||
}
|
||||
|
||||
public static int getProviderType(int dim)
|
||||
{
|
||||
if (!dimensions.containsKey(dim))
|
||||
{
|
||||
throw new IllegalArgumentException(String.format("Could not get provider type for dimension %d, does not exist", dim));
|
||||
}
|
||||
return dimensions.get(dim);
|
||||
}
|
||||
|
||||
public static WorldProvider getProvider(int dim)
|
||||
{
|
||||
return getWorld(dim).provider;
|
||||
}
|
||||
|
||||
public static Integer[] getIDs(boolean check)
|
||||
{
|
||||
if (check)
|
||||
{
|
||||
List<World> allWorlds = Lists.newArrayList(weakWorldMap.keySet());
|
||||
allWorlds.removeAll(worlds.values());
|
||||
for (ListIterator<World> li = allWorlds.listIterator(); li.hasNext(); )
|
||||
{
|
||||
World w = li.next();
|
||||
leakedWorlds.add(System.identityHashCode(w));
|
||||
}
|
||||
for (World w : allWorlds)
|
||||
{
|
||||
int leakCount = leakedWorlds.count(System.identityHashCode(w));
|
||||
if (leakCount == 5)
|
||||
{
|
||||
FMLLog.fine("The world %x (%s) may have leaked: first encounter (5 occurences).\n", System.identityHashCode(w), w.getWorldInfo().getWorldName());
|
||||
}
|
||||
else if (leakCount % 5 == 0)
|
||||
{
|
||||
FMLLog.fine("The world %x (%s) may have leaked: seen %d times.\n", System.identityHashCode(w), w.getWorldInfo().getWorldName(), leakCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
return getIDs();
|
||||
}
|
||||
public static Integer[] getIDs()
|
||||
{
|
||||
return worlds.keySet().toArray(new Integer[worlds.size()]); //Only loaded dims, since usually used to cycle through loaded worlds
|
||||
}
|
||||
|
||||
public static void setWorld(int id, WorldServer world)
|
||||
{
|
||||
if (world != null)
|
||||
{
|
||||
worlds.put(id, world);
|
||||
weakWorldMap.put(world, world);
|
||||
MinecraftServer.getServer().worldTickTimes.put(id, new long[100]);
|
||||
FMLLog.info("Loading dimension %d (%s) (%s)", id, world.getWorldInfo().getWorldName(), world.getMinecraftServer());
|
||||
}
|
||||
else
|
||||
{
|
||||
worlds.remove(id);
|
||||
MinecraftServer.getServer().worldTickTimes.remove(id);
|
||||
FMLLog.info("Unloading dimension %d", id);
|
||||
}
|
||||
|
||||
ArrayList<WorldServer> tmp = new ArrayList<WorldServer>();
|
||||
if (worlds.get( 0) != null)
|
||||
tmp.add(worlds.get( 0));
|
||||
if (worlds.get(-1) != null)
|
||||
tmp.add(worlds.get(-1));
|
||||
if (worlds.get( 1) != null)
|
||||
tmp.add(worlds.get( 1));
|
||||
|
||||
for (Entry<Integer, WorldServer> entry : worlds.entrySet())
|
||||
{
|
||||
int dim = entry.getKey();
|
||||
if (dim >= -1 && dim <= 1)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
tmp.add(entry.getValue());
|
||||
}
|
||||
|
||||
MinecraftServer.getServer().worldServers = tmp.toArray(new WorldServer[tmp.size()]);
|
||||
}
|
||||
|
||||
public static void initDimension(int dim) {
|
||||
WorldServer overworld = getWorld(0);
|
||||
if (overworld == null)
|
||||
{
|
||||
throw new RuntimeException("Cannot Hotload Dim: Overworld is not Loaded!");
|
||||
}
|
||||
try
|
||||
{
|
||||
DimensionManager.getProviderType(dim);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
System.err.println("Cannot Hotload Dim: " + e.getMessage());
|
||||
return; // If a provider hasn't been registered then we can't hotload the dim
|
||||
}
|
||||
MinecraftServer mcServer = overworld.getMinecraftServer();
|
||||
ISaveHandler savehandler = overworld.getSaveHandler();
|
||||
WorldSettings worldSettings = new WorldSettings(overworld.getWorldInfo());
|
||||
|
||||
WorldServer world = (dim == 0 ? overworld : new WorldServerMulti(mcServer, savehandler, overworld.getWorldInfo().getWorldName(), dim, worldSettings, overworld, mcServer.theProfiler, overworld.getWorldLogAgent()));
|
||||
world.addWorldAccess(new WorldManager(mcServer, world));
|
||||
MinecraftForge.EVENT_BUS.post(new WorldEvent.Load(world));
|
||||
if (!mcServer.isSinglePlayer())
|
||||
{
|
||||
world.getWorldInfo().setGameType(mcServer.getGameType());
|
||||
}
|
||||
|
||||
mcServer.setDifficultyForAllWorlds(mcServer.getDifficulty());
|
||||
}
|
||||
|
||||
public static WorldServer getWorld(int id)
|
||||
{
|
||||
return worlds.get(id);
|
||||
}
|
||||
|
||||
public static WorldServer[] getWorlds()
|
||||
{
|
||||
return worlds.values().toArray(new WorldServer[worlds.size()]);
|
||||
}
|
||||
|
||||
public static boolean shouldLoadSpawn(int dim)
|
||||
{
|
||||
int id = getProviderType(dim);
|
||||
return spawnSettings.containsKey(id) && spawnSettings.get(id);
|
||||
}
|
||||
|
||||
static
|
||||
{
|
||||
init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Not public API: used internally to get dimensions that should load at
|
||||
* server startup
|
||||
*/
|
||||
public static Integer[] getStaticDimensionIDs()
|
||||
{
|
||||
return dimensions.keySet().toArray(new Integer[dimensions.keySet().size()]);
|
||||
}
|
||||
public static WorldProvider createProviderFor(int dim)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (dimensions.containsKey(dim))
|
||||
{
|
||||
WorldProvider provider = providers.get(getProviderType(dim)).newInstance();
|
||||
provider.setDimension(dim);
|
||||
return provider;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new RuntimeException(String.format("No WorldProvider bound for dimension %d", dim)); //It's going to crash anyway at this point. Might as well be informative
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
FMLCommonHandler.instance().getFMLLogger().log(Level.SEVERE,String.format("An error occured trying to create an instance of WorldProvider %d (%s)",
|
||||
dim, providers.get(getProviderType(dim)).getSimpleName()),e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void unloadWorld(int id) {
|
||||
unloadQueue.add(id);
|
||||
}
|
||||
|
||||
/*
|
||||
* To be called by the server at the appropriate time, do not call from mod code.
|
||||
*/
|
||||
public static void unloadWorlds(Hashtable<Integer, long[]> worldTickTimes) {
|
||||
for (int id : unloadQueue) {
|
||||
WorldServer w = worlds.get(id);
|
||||
try {
|
||||
if (w != null)
|
||||
{
|
||||
w.saveAllChunks(true, null);
|
||||
}
|
||||
else
|
||||
{
|
||||
FMLLog.warning("Unexpected world unload - world %d is already unloaded", id);
|
||||
}
|
||||
} catch (MinecraftException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (w != null)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(w));
|
||||
w.flush();
|
||||
setWorld(id, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
unloadQueue.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the next free dimension ID. Note: you are not guaranteed a contiguous
|
||||
* block of free ids. Always call for each individual ID you wish to get.
|
||||
* @return the next free dimension ID
|
||||
*/
|
||||
public static int getNextFreeDimId() {
|
||||
int next = 0;
|
||||
while (true)
|
||||
{
|
||||
next = dimensionMap.nextClearBit(next);
|
||||
if (dimensions.containsKey(next))
|
||||
{
|
||||
dimensionMap.set(next);
|
||||
}
|
||||
else
|
||||
{
|
||||
return next;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static NBTTagCompound saveDimensionDataMap()
|
||||
{
|
||||
int[] data = new int[(dimensionMap.length() + Integer.SIZE - 1 )/ Integer.SIZE];
|
||||
NBTTagCompound dimMap = new NBTTagCompound();
|
||||
for (int i = 0; i < data.length; i++)
|
||||
{
|
||||
int val = 0;
|
||||
for (int j = 0; j < Integer.SIZE; j++)
|
||||
{
|
||||
val |= dimensionMap.get(i * Integer.SIZE + j) ? (1 << j) : 0;
|
||||
}
|
||||
data[i] = val;
|
||||
}
|
||||
dimMap.setIntArray("DimensionArray", data);
|
||||
return dimMap;
|
||||
}
|
||||
|
||||
public static void loadDimensionDataMap(NBTTagCompound compoundTag)
|
||||
{
|
||||
if (compoundTag == null)
|
||||
{
|
||||
dimensionMap.clear();
|
||||
for (Integer id : dimensions.keySet())
|
||||
{
|
||||
if (id >= 0)
|
||||
{
|
||||
dimensionMap.set(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int[] intArray = compoundTag.getIntArray("DimensionArray");
|
||||
for (int i = 0; i < intArray.length; i++)
|
||||
{
|
||||
for (int j = 0; j < Integer.SIZE; j++)
|
||||
{
|
||||
dimensionMap.set(i * Integer.SIZE + j, (intArray[i] & (1 << j)) != 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the current root directory for the world save. Accesses getSaveHandler from the overworld
|
||||
* @return the root directory of the save
|
||||
*/
|
||||
public static File getCurrentSaveRootDirectory()
|
||||
{
|
||||
if (DimensionManager.getWorld(0) != null)
|
||||
{
|
||||
return ((SaveHandler)DimensionManager.getWorld(0).getSaveHandler()).getWorldDirectory();
|
||||
}
|
||||
else if (MinecraftServer.getServer() != null)
|
||||
{
|
||||
MinecraftServer srv = MinecraftServer.getServer();
|
||||
SaveHandler saveHandler = (SaveHandler) srv.getActiveAnvilConverter().getSaveLoader(srv.getFolderName(), false);
|
||||
return saveHandler.getWorldDirectory();
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Random;
|
||||
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
|
||||
import net.minecraft.inventory.IInventory;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.WeightedRandom;
|
||||
import net.minecraft.util.WeightedRandomChestContent;
|
||||
import net.minecraft.util.WeightedRandomItem;
|
||||
|
||||
import static net.minecraftforge.common.ChestGenHooks.DUNGEON_CHEST;
|
||||
|
||||
public class DungeonHooks
|
||||
{
|
||||
private static ArrayList<DungeonMob> dungeonMobs = new ArrayList<DungeonMob>();
|
||||
|
||||
/**
|
||||
* Adds a mob to the possible list of creatures the spawner will create.
|
||||
* If the mob is already in the spawn list, the rarity will be added to the existing one,
|
||||
* causing the mob to be more common.
|
||||
*
|
||||
* @param name The name of the monster, use the same name used when registering the entity.
|
||||
* @param rarity The rarity of selecting this mob over others. Must be greater then 0.
|
||||
* Vanilla Minecraft has the following mobs:
|
||||
* Spider 100
|
||||
* Skeleton 100
|
||||
* Zombie 200
|
||||
* Meaning, Zombies are twice as common as spiders or skeletons.
|
||||
* @return The new rarity of the monster,
|
||||
*/
|
||||
public static float addDungeonMob(String name, int rarity)
|
||||
{
|
||||
if (rarity <= 0)
|
||||
{
|
||||
throw new IllegalArgumentException("Rarity must be greater then zero");
|
||||
}
|
||||
|
||||
for (DungeonMob mob : dungeonMobs)
|
||||
{
|
||||
if (name.equals(mob.type))
|
||||
{
|
||||
return mob.itemWeight += rarity;
|
||||
}
|
||||
}
|
||||
|
||||
dungeonMobs.add(new DungeonMob(rarity, name));
|
||||
return rarity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Will completely remove a Mob from the dungeon spawn list.
|
||||
*
|
||||
* @param name The name of the mob to remove
|
||||
* @return The rarity of the removed mob, prior to being removed.
|
||||
*/
|
||||
public static int removeDungeonMob(String name)
|
||||
{
|
||||
for (DungeonMob mob : dungeonMobs)
|
||||
{
|
||||
if (name.equals(mob.type))
|
||||
{
|
||||
dungeonMobs.remove(mob);
|
||||
return mob.itemWeight;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a random mob name from the list.
|
||||
* @param rand World generation random number generator
|
||||
* @return The mob name
|
||||
*/
|
||||
public static String getRandomDungeonMob(Random rand)
|
||||
{
|
||||
DungeonMob mob = (DungeonMob)WeightedRandom.getRandomItem(rand, dungeonMobs);
|
||||
if (mob == null)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
return mob.type;
|
||||
}
|
||||
|
||||
|
||||
public static class DungeonMob extends WeightedRandomItem
|
||||
{
|
||||
public String type;
|
||||
public DungeonMob(int weight, String type)
|
||||
{
|
||||
super(weight);
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object target)
|
||||
{
|
||||
return target instanceof DungeonMob && type.equals(((DungeonMob)target).type);
|
||||
}
|
||||
}
|
||||
|
||||
static
|
||||
{
|
||||
addDungeonMob("Skeleton", 100);
|
||||
addDungeonMob("Zombie", 200);
|
||||
addDungeonMob("Spider", 100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
import cpw.mods.fml.common.FMLCommonHandler;
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
|
||||
import net.minecraft.block.EnumMobType;
|
||||
import net.minecraft.block.material.Material;
|
||||
import net.minecraft.enchantment.EnumEnchantmentType;
|
||||
import net.minecraft.entity.EnumCreatureAttribute;
|
||||
import net.minecraft.entity.EnumCreatureType;
|
||||
import net.minecraft.entity.EnumEntitySize;
|
||||
import net.minecraft.entity.player.EnumStatus;
|
||||
import net.minecraft.item.EnumAction;
|
||||
import net.minecraft.item.EnumArmorMaterial;
|
||||
import net.minecraft.item.EnumToolMaterial;
|
||||
import net.minecraft.util.EnumArt;
|
||||
import net.minecraft.util.EnumMovingObjectType;
|
||||
import net.minecraft.world.EnumSkyBlock;
|
||||
import net.minecraft.world.gen.structure.EnumDoor;
|
||||
import net.minecraftforge.classloading.FMLForgePlugin;
|
||||
|
||||
public class EnumHelper
|
||||
{
|
||||
private static Object reflectionFactory = null;
|
||||
private static Method newConstructorAccessor = null;
|
||||
private static Method newInstance = null;
|
||||
private static Method newFieldAccessor = null;
|
||||
private static Method fieldAccessorSet = null;
|
||||
private static boolean isSetup = false;
|
||||
|
||||
//Some enums are decompiled with extra arguments, so lets check for that
|
||||
private static Class[][] commonTypes =
|
||||
{
|
||||
{EnumAction.class},
|
||||
{EnumArmorMaterial.class, int.class, int[].class, int.class},
|
||||
{EnumArt.class, String.class, int.class, int.class, int.class, int.class},
|
||||
{EnumCreatureAttribute.class},
|
||||
{EnumCreatureType.class, Class.class, int.class, Material.class, boolean.class},
|
||||
{EnumDoor.class},
|
||||
{EnumEnchantmentType.class},
|
||||
{EnumEntitySize.class},
|
||||
{EnumMobType.class},
|
||||
{EnumMovingObjectType.class},
|
||||
{EnumSkyBlock.class, int.class},
|
||||
{EnumStatus.class},
|
||||
{EnumToolMaterial.class, int.class, int.class, float.class, float.class, int.class}
|
||||
};
|
||||
|
||||
public static EnumAction addAction(String name)
|
||||
{
|
||||
return addEnum(EnumAction.class, name);
|
||||
}
|
||||
public static EnumArmorMaterial addArmorMaterial(String name, int durability, int[] reductionAmounts, int enchantability)
|
||||
{
|
||||
return addEnum(EnumArmorMaterial.class, name, durability, reductionAmounts, enchantability);
|
||||
}
|
||||
public static EnumArt addArt(String name, String tile, int sizeX, int sizeY, int offsetX, int offsetY)
|
||||
{
|
||||
return addEnum(EnumArt.class, name, tile, sizeX, sizeY, offsetX, offsetY);
|
||||
}
|
||||
public static EnumCreatureAttribute addCreatureAttribute(String name)
|
||||
{
|
||||
return addEnum(EnumCreatureAttribute.class, name);
|
||||
}
|
||||
public static EnumCreatureType addCreatureType(String name, Class typeClass, int maxNumber, Material material, boolean peaceful)
|
||||
{
|
||||
return addEnum(EnumCreatureType.class, name, typeClass, maxNumber, material, peaceful);
|
||||
}
|
||||
public static EnumDoor addDoor(String name)
|
||||
{
|
||||
return addEnum(EnumDoor.class, name);
|
||||
}
|
||||
public static EnumEnchantmentType addEnchantmentType(String name)
|
||||
{
|
||||
return addEnum(EnumEnchantmentType.class, name);
|
||||
}
|
||||
public static EnumEntitySize addEntitySize(String name)
|
||||
{
|
||||
return addEnum(EnumEntitySize.class, name);
|
||||
}
|
||||
public static EnumMobType addMobType(String name)
|
||||
{
|
||||
return addEnum(EnumMobType.class, name);
|
||||
}
|
||||
public static EnumMovingObjectType addMovingObjectType(String name)
|
||||
{
|
||||
if (!isSetup)
|
||||
{
|
||||
setup();
|
||||
}
|
||||
|
||||
return addEnum(EnumMovingObjectType.class, name);
|
||||
}
|
||||
public static EnumSkyBlock addSkyBlock(String name, int lightValue)
|
||||
{
|
||||
return addEnum(EnumSkyBlock.class, name, lightValue);
|
||||
}
|
||||
public static EnumStatus addStatus(String name)
|
||||
{
|
||||
return addEnum(EnumStatus.class, name);
|
||||
}
|
||||
public static EnumToolMaterial addToolMaterial(String name, int harvestLevel, int maxUses, float efficiency, float damage, int enchantability)
|
||||
{
|
||||
return addEnum(EnumToolMaterial.class, name, harvestLevel, maxUses, efficiency, damage, enchantability);
|
||||
}
|
||||
|
||||
private static void setup()
|
||||
{
|
||||
if (isSetup)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Method getReflectionFactory = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("getReflectionFactory");
|
||||
reflectionFactory = getReflectionFactory.invoke(null);
|
||||
newConstructorAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newConstructorAccessor", Constructor.class);
|
||||
newInstance = Class.forName("sun.reflect.ConstructorAccessor").getDeclaredMethod("newInstance", Object[].class);
|
||||
newFieldAccessor = Class.forName("sun.reflect.ReflectionFactory").getDeclaredMethod("newFieldAccessor", Field.class, boolean.class);
|
||||
fieldAccessorSet = Class.forName("sun.reflect.FieldAccessor").getDeclaredMethod("set", Object.class, Object.class);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
isSetup = true;
|
||||
}
|
||||
|
||||
/*
|
||||
* 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 Object getConstructorAccessor(Class<?> enumClass, Class<?>[] additionalParameterTypes) throws Exception
|
||||
{
|
||||
Class<?>[] parameterTypes = new Class[additionalParameterTypes.length + 2];
|
||||
parameterTypes[0] = String.class;
|
||||
parameterTypes[1] = int.class;
|
||||
System.arraycopy(additionalParameterTypes, 0, parameterTypes, 2, additionalParameterTypes.length);
|
||||
return newConstructorAccessor.invoke(reflectionFactory, enumClass.getDeclaredConstructor(parameterTypes));
|
||||
}
|
||||
|
||||
private static < T extends Enum<? >> T makeEnum(Class<T> enumClass, String value, int ordinal, Class<?>[] additionalTypes, Object[] additionalValues) throws Exception
|
||||
{
|
||||
Object[] parms = new Object[additionalValues.length + 2];
|
||||
parms[0] = value;
|
||||
parms[1] = Integer.valueOf(ordinal);
|
||||
System.arraycopy(additionalValues, 0, parms, 2, additionalValues.length);
|
||||
return enumClass.cast(newInstance.invoke(getConstructorAccessor(enumClass, additionalTypes), new Object[] {parms}));
|
||||
}
|
||||
|
||||
public static void setFailsafeFieldValue(Field field, Object target, Object value) throws Exception
|
||||
{
|
||||
field.setAccessible(true);
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
modifiersField.setAccessible(true);
|
||||
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
|
||||
Object fieldAccessor = newFieldAccessor.invoke(reflectionFactory, field, false);
|
||||
fieldAccessorSet.invoke(fieldAccessor, target, value);
|
||||
}
|
||||
|
||||
private static void blankField(Class<?> enumClass, String fieldName) throws Exception
|
||||
{
|
||||
for (Field field : Class.class.getDeclaredFields())
|
||||
{
|
||||
if (field.getName().contains(fieldName))
|
||||
{
|
||||
field.setAccessible(true);
|
||||
setFailsafeFieldValue(field, enumClass, null);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void cleanEnumCache(Class<?> enumClass) throws Exception
|
||||
{
|
||||
blankField(enumClass, "enumConstantDirectory");
|
||||
blankField(enumClass, "enumConstants");
|
||||
}
|
||||
|
||||
public static <T extends Enum<? >> T addEnum(Class<T> enumType, String enumName, Object... paramValues)
|
||||
{
|
||||
return addEnum(commonTypes, enumType, enumName, paramValues);
|
||||
}
|
||||
|
||||
public static <T extends Enum<? >> T addEnum(Class[][] map, Class<T> enumType, String enumName, Object... paramValues)
|
||||
{
|
||||
for (Class[] lookup : map)
|
||||
{
|
||||
if (lookup[0] == enumType)
|
||||
{
|
||||
Class<?>[] paramTypes = new Class<?>[lookup.length - 1];
|
||||
if (paramTypes.length > 0)
|
||||
{
|
||||
System.arraycopy(lookup, 1, paramTypes, 0, paramTypes.length);
|
||||
}
|
||||
return addEnum(enumType, enumName, paramTypes, paramValues);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T extends Enum<? >> T addEnum(Class<T> enumType, String enumName, Class<?>[] paramTypes, Object[] paramValues)
|
||||
{
|
||||
if (!isSetup)
|
||||
{
|
||||
setup();
|
||||
}
|
||||
|
||||
Field valuesField = null;
|
||||
Field[] fields = enumType.getDeclaredFields();
|
||||
|
||||
for (Field field : fields)
|
||||
{
|
||||
String name = field.getName();
|
||||
if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
|
||||
{
|
||||
valuesField = field;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
|
||||
if (valuesField == null)
|
||||
{
|
||||
String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));
|
||||
|
||||
for (Field field : fields)
|
||||
{
|
||||
if ((field.getModifiers() & flags) == flags &&
|
||||
field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
|
||||
{
|
||||
valuesField = field;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (valuesField == null)
|
||||
{
|
||||
FMLLog.severe("Could not find $VALUES field for enum: %s", enumType.getName());
|
||||
FMLLog.severe("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF);
|
||||
FMLLog.severe("Flags: %s", String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0'));
|
||||
FMLLog.severe("Fields:");
|
||||
for (Field field : fields)
|
||||
{
|
||||
String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
|
||||
FMLLog.severe(" %s %s: %s", mods, field.getName(), field.getType().getName());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
valuesField.setAccessible(true);
|
||||
|
||||
try
|
||||
{
|
||||
T[] previousValues = (T[])valuesField.get(enumType);
|
||||
List<T> values = new ArrayList<T>(Arrays.asList(previousValues));
|
||||
T newValue = (T)makeEnum(enumType, enumName, values.size(), paramTypes, paramValues);
|
||||
values.add(newValue);
|
||||
setFailsafeFieldValue(valuesField, null, values.toArray((T[]) Array.newInstance(enumType, 0)));
|
||||
cleanEnumCache(enumType);
|
||||
|
||||
return newValue;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
static
|
||||
{
|
||||
if (!isSetup)
|
||||
{
|
||||
setup();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
public enum EnumPlantType
|
||||
{
|
||||
Plains,
|
||||
Desert,
|
||||
Beach,
|
||||
Cave,
|
||||
Water,
|
||||
Nether,
|
||||
Crop
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import cpw.mods.fml.common.FMLCommonHandler;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.item.ItemInWorldManager;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.util.ChatMessageComponent;
|
||||
import net.minecraft.util.ChunkCoordinates;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
//Preliminary, simple Fake Player class
|
||||
public class FakePlayer extends EntityPlayerMP
|
||||
{
|
||||
public FakePlayer(World world, String name)
|
||||
{
|
||||
super(FMLCommonHandler.instance().getMinecraftServerInstance(), world, name, new ItemInWorldManager(world));
|
||||
}
|
||||
|
||||
public void sendChatToPlayer(String s){}
|
||||
public boolean canCommandSenderUseCommand(int i, String s){ return false; }
|
||||
public ChunkCoordinates getPlayerCoordinates()
|
||||
{
|
||||
return new ChunkCoordinates(0,0,0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendChatToPlayer(ChatMessageComponent chatmessagecomponent){}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.world.World;
|
||||
|
||||
//To be expanded for generic Mod fake players?
|
||||
public class FakePlayerFactory
|
||||
{
|
||||
// Map of all active fake player usernames to their entities
|
||||
private static java.util.Map<String, FakePlayer> fakePlayers = new java.util.HashMap<String, FakePlayer>();
|
||||
private static FakePlayer MINECRAFT_PLAYER = null;
|
||||
|
||||
public static FakePlayer getMinecraft(World world)
|
||||
{
|
||||
if (MINECRAFT_PLAYER == null)
|
||||
{
|
||||
MINECRAFT_PLAYER = FakePlayerFactory.get(world, "[Minecraft]");
|
||||
}
|
||||
return MINECRAFT_PLAYER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a fake player with a given username
|
||||
*/
|
||||
public static FakePlayer get(World world, String username)
|
||||
{
|
||||
if (!fakePlayers.containsKey(username))
|
||||
{
|
||||
FakePlayer fakePlayer = new FakePlayer(world, username);
|
||||
fakePlayers.put(username, fakePlayer);
|
||||
}
|
||||
|
||||
return fakePlayers.get(username);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,71 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
public enum ForgeDirection
|
||||
{
|
||||
/** -Y */
|
||||
DOWN(0, -1, 0),
|
||||
|
||||
/** +Y */
|
||||
UP(0, 1, 0),
|
||||
|
||||
/** -Z */
|
||||
NORTH(0, 0, -1),
|
||||
|
||||
/** +Z */
|
||||
SOUTH(0, 0, 1),
|
||||
|
||||
/** -X */
|
||||
WEST(-1, 0, 0),
|
||||
|
||||
/** +X */
|
||||
EAST(1, 0, 0),
|
||||
|
||||
/**
|
||||
* Used only by getOrientation, for invalid inputs
|
||||
*/
|
||||
UNKNOWN(0, 0, 0);
|
||||
|
||||
public final int offsetX;
|
||||
public final int offsetY;
|
||||
public final int offsetZ;
|
||||
public final int flag;
|
||||
public static final ForgeDirection[] VALID_DIRECTIONS = {DOWN, UP, NORTH, SOUTH, WEST, EAST};
|
||||
public static final int[] OPPOSITES = {1, 0, 3, 2, 5, 4, 6};
|
||||
// Left hand rule rotation matrix for all possible axes of rotation
|
||||
public static final int[][] ROTATION_MATRIX = {
|
||||
{0, 1, 4, 5, 3, 2, 6},
|
||||
{0, 1, 5, 4, 2, 3, 6},
|
||||
{5, 4, 2, 3, 0, 1, 6},
|
||||
{4, 5, 2, 3, 1, 0, 6},
|
||||
{2, 3, 1, 0, 4, 5, 6},
|
||||
{3, 2, 0, 1, 4, 5, 6},
|
||||
{0, 1, 2, 3, 4, 5, 6},
|
||||
};
|
||||
|
||||
private ForgeDirection(int x, int y, int z)
|
||||
{
|
||||
offsetX = x;
|
||||
offsetY = y;
|
||||
offsetZ = z;
|
||||
flag = 1 << ordinal();
|
||||
}
|
||||
|
||||
public static ForgeDirection getOrientation(int id)
|
||||
{
|
||||
if (id >= 0 && id < VALID_DIRECTIONS.length)
|
||||
{
|
||||
return VALID_DIRECTIONS[id];
|
||||
}
|
||||
return UNKNOWN;
|
||||
}
|
||||
|
||||
public ForgeDirection getOpposite()
|
||||
{
|
||||
return getOrientation(OPPOSITES[ordinal()]);
|
||||
}
|
||||
|
||||
public ForgeDirection getRotation(ForgeDirection axis)
|
||||
{
|
||||
return getOrientation(ROTATION_MATRIX[axis.ordinal()][ordinal()]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import net.minecraft.nbt.NBTBase;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.server.management.PlayerInstance;
|
||||
import net.minecraft.world.storage.SaveHandler;
|
||||
import net.minecraft.world.storage.WorldInfo;
|
||||
import net.minecraftforge.classloading.FMLForgePlugin;
|
||||
import net.minecraftforge.common.network.ForgeConnectionHandler;
|
||||
import net.minecraftforge.common.network.ForgeNetworkHandler;
|
||||
import net.minecraftforge.common.network.ForgePacketHandler;
|
||||
import net.minecraftforge.common.network.ForgeTinyPacketHandler;
|
||||
import net.minecraftforge.oredict.RecipeSorter;
|
||||
import net.minecraftforge.server.command.ForgeCommand;
|
||||
|
||||
import com.google.common.eventbus.EventBus;
|
||||
import com.google.common.eventbus.Subscribe;
|
||||
|
||||
import cpw.mods.fml.client.FMLFileResourcePack;
|
||||
import cpw.mods.fml.client.FMLFolderResourcePack;
|
||||
import cpw.mods.fml.common.DummyModContainer;
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
import cpw.mods.fml.common.LoadController;
|
||||
import cpw.mods.fml.common.Loader;
|
||||
import cpw.mods.fml.common.ModMetadata;
|
||||
import cpw.mods.fml.common.WorldAccessContainer;
|
||||
import cpw.mods.fml.common.event.FMLConstructionEvent;
|
||||
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
|
||||
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
|
||||
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
|
||||
import cpw.mods.fml.common.event.FMLServerStartingEvent;
|
||||
import cpw.mods.fml.common.network.FMLNetworkHandler;
|
||||
import cpw.mods.fml.common.network.NetworkMod;
|
||||
import static net.minecraftforge.common.ForgeVersion.*;
|
||||
import static net.minecraftforge.common.Configuration.*;
|
||||
|
||||
@NetworkMod(
|
||||
channels = "FORGE",
|
||||
connectionHandler = ForgeConnectionHandler.class,
|
||||
packetHandler = ForgePacketHandler.class,
|
||||
tinyPacketHandler = ForgeTinyPacketHandler.class
|
||||
)
|
||||
public class ForgeDummyContainer extends DummyModContainer implements WorldAccessContainer
|
||||
{
|
||||
public static int clumpingThreshold = 64;
|
||||
public static boolean removeErroringEntities = false;
|
||||
public static boolean removeErroringTileEntities = false;
|
||||
public static boolean disableStitchedFileSaving = false;
|
||||
public static boolean forceDuplicateFluidBlockCrash = true;
|
||||
public static boolean fullBoundingBoxLadders = false;
|
||||
public static double zombieSummonBaseChance = 0.1;
|
||||
public static int[] blendRanges = { 20, 15, 10, 5 };
|
||||
public static float zombieBabyChance = 0.05f;
|
||||
public static boolean shouldSortRecipies = false;
|
||||
|
||||
public ForgeDummyContainer()
|
||||
{
|
||||
super(new ModMetadata());
|
||||
ModMetadata meta = getMetadata();
|
||||
meta.modId = "Forge";
|
||||
meta.name = "Minecraft Forge";
|
||||
meta.version = String.format("%d.%d.%d.%d", majorVersion, minorVersion, revisionVersion, buildVersion);
|
||||
meta.credits = "Made possible with help from many people";
|
||||
meta.authorList = Arrays.asList("LexManos", "Eloraam", "Spacetoad");
|
||||
meta.description = "Minecraft Forge is a common open source API allowing a broad range of mods " +
|
||||
"to work cooperatively together. It allows many mods to be created without " +
|
||||
"them editing the main Minecraft code.";
|
||||
meta.url = "http://MinecraftForge.net";
|
||||
meta.updateUrl = "http://MinecraftForge.net/forum/index.php/topic,5.0.html";
|
||||
meta.screenshots = new String[0];
|
||||
meta.logoFile = "/forge_logo.png";
|
||||
|
||||
Configuration config = null;
|
||||
File cfgFile = new File(Loader.instance().getConfigDir(), "forge.cfg");
|
||||
try
|
||||
{
|
||||
config = new Configuration(cfgFile);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
System.out.println("Error loading forge.cfg, deleting file and resetting: ");
|
||||
e.printStackTrace();
|
||||
|
||||
if (cfgFile.exists())
|
||||
cfgFile.delete();
|
||||
|
||||
config = new Configuration(cfgFile);
|
||||
}
|
||||
if (!config.isChild)
|
||||
{
|
||||
config.load();
|
||||
Property enableGlobalCfg = config.get(Configuration.CATEGORY_GENERAL, "enableGlobalConfig", false);
|
||||
if (enableGlobalCfg.getBoolean(false))
|
||||
{
|
||||
Configuration.enableGlobalConfig();
|
||||
}
|
||||
}
|
||||
Property prop;
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "clumpingThreshold", 64);
|
||||
prop.comment = "Controls the number threshold at which Packet51 is preferred over Packet52, default and minimum 64, maximum 1024";
|
||||
clumpingThreshold = prop.getInt(64);
|
||||
if (clumpingThreshold > 1024 || clumpingThreshold < 64)
|
||||
{
|
||||
clumpingThreshold = 64;
|
||||
prop.set(64);
|
||||
}
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "removeErroringEntities", false);
|
||||
prop.comment = "Set this to just remove any TileEntity that throws a error in there update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES.";
|
||||
removeErroringEntities = prop.getBoolean(false);
|
||||
|
||||
if (removeErroringEntities)
|
||||
{
|
||||
FMLLog.warning("Enabling removal of erroring Entities - USE AT YOUR OWN RISK");
|
||||
}
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "removeErroringTileEntities", false);
|
||||
prop.comment = "Set this to just remove any TileEntity that throws a error in there update method instead of closing the server and reporting a crash log. BE WARNED THIS COULD SCREW UP EVERYTHING USE SPARINGLY WE ARE NOT RESPONSIBLE FOR DAMAGES.";
|
||||
removeErroringTileEntities = prop.getBoolean(false);
|
||||
|
||||
if (removeErroringTileEntities)
|
||||
{
|
||||
FMLLog.warning("Enabling removal of erroring Tile Entities - USE AT YOUR OWN RISK");
|
||||
}
|
||||
|
||||
//prop = config.get(Configuration.CATEGORY_GENERAL, "disableStitchedFileSaving", true);
|
||||
//prop.comment = "Set this to just disable the texture stitcher from writing the 'debug.stitched_{name}.png file to disc. Just a small performance tweak. Default: true";
|
||||
//disableStitchedFileSaving = prop.getBoolean(true);
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "fullBoundingBoxLadders", false);
|
||||
prop.comment = "Set this to check the entire entity's collision bounding box for ladders instead of just the block they are in. Causes noticable differences in mechanics so default is vanilla behavior. Default: false";
|
||||
fullBoundingBoxLadders = prop.getBoolean(false);
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "forceDuplicateFluidBlockCrash", true);
|
||||
prop.comment = "Set this to force a crash if more than one block attempts to link back to the same Fluid. Enabled by default.";
|
||||
forceDuplicateFluidBlockCrash = prop.getBoolean(true);
|
||||
|
||||
if (!forceDuplicateFluidBlockCrash)
|
||||
{
|
||||
FMLLog.warning("Disabling forced crashes on duplicate Fluid Blocks - USE AT YOUR OWN RISK");
|
||||
}
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "biomeSkyBlendRange", new int[] { 20, 15, 10, 5 });
|
||||
prop.comment = "Control the range of sky blending for colored skies in biomes.";
|
||||
blendRanges = prop.getIntList();
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "zombieBaseSummonChance", 0.1);
|
||||
prop.comment = "Base zombie summoning spawn chance. Allows changing the bonus zombie summoning mechanic.";
|
||||
zombieSummonBaseChance = prop.getDouble(0.1);
|
||||
|
||||
prop = config.get(Configuration.CATEGORY_GENERAL, "zombieBabyChance", 0.05);
|
||||
prop.comment = "Chance that a zombie (or subclass) is a baby. Allows changing the zombie spawning mechanic.";
|
||||
zombieBabyChance = (float) prop.getDouble(0.05);
|
||||
|
||||
prop = config.get(CATEGORY_GENERAL, "sortRecipies", shouldSortRecipies);
|
||||
prop.comment = "Set to true to enable the post initlization sorting of crafting recipes using Froge's sorter. May cause desyncing on conflicting recipies. ToDo: Set to true by default in 1.7";
|
||||
shouldSortRecipies = prop.getBoolean(shouldSortRecipies);
|
||||
|
||||
if (config.hasChanged())
|
||||
{
|
||||
config.save();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean registerBus(EventBus bus, LoadController controller)
|
||||
{
|
||||
bus.register(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void modConstruction(FMLConstructionEvent evt)
|
||||
{
|
||||
FMLLog.info("Registering Forge Packet Handler");
|
||||
try
|
||||
{
|
||||
FMLNetworkHandler.instance().registerNetworkMod(new ForgeNetworkHandler(this));
|
||||
FMLLog.info("Succeeded registering Forge Packet Handler");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
FMLLog.log(Level.SEVERE, e, "Failed to register packet handler for Forge");
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void preInit(FMLPreInitializationEvent evt)
|
||||
{
|
||||
ForgeChunkManager.captureConfig(evt.getModConfigurationDirectory());
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void postInit(FMLPostInitializationEvent evt)
|
||||
{
|
||||
BiomeDictionary.registerAllBiomesAndGenerateEvents();
|
||||
ForgeChunkManager.loadConfiguration();
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void onAvalible(FMLLoadCompleteEvent evt)
|
||||
{
|
||||
if (shouldSortRecipies)
|
||||
{
|
||||
RecipeSorter.sortCraftManager();
|
||||
}
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void serverStarting(FMLServerStartingEvent evt)
|
||||
{
|
||||
evt.registerServerCommand(new ForgeCommand(evt.getServer()));
|
||||
}
|
||||
@Override
|
||||
public NBTTagCompound getDataForWriting(SaveHandler handler, WorldInfo info)
|
||||
{
|
||||
NBTTagCompound forgeData = new NBTTagCompound();
|
||||
NBTTagCompound dimData = DimensionManager.saveDimensionDataMap();
|
||||
forgeData.setCompoundTag("DimensionData", dimData);
|
||||
return forgeData;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void readData(SaveHandler handler, WorldInfo info, Map<String, NBTBase> propertyMap, NBTTagCompound tag)
|
||||
{
|
||||
if (tag.hasKey("DimensionData"))
|
||||
{
|
||||
DimensionManager.loadDimensionDataMap(tag.hasKey("DimensionData") ? tag.getCompoundTag("DimensionData") : null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public File getSource()
|
||||
{
|
||||
return FMLForgePlugin.forgeLocation;
|
||||
}
|
||||
@Override
|
||||
public Class<?> getCustomResourcePackClass()
|
||||
{
|
||||
if (getSource().isDirectory())
|
||||
{
|
||||
return FMLFolderResourcePack.class;
|
||||
}
|
||||
else
|
||||
{
|
||||
return FMLFileResourcePack.class;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.enchantment.EnchantmentHelper;
|
||||
import net.minecraft.entity.EntityLiving;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.entity.item.EntityItem;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.inventory.Container;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemArmor;
|
||||
import net.minecraft.item.ItemAxe;
|
||||
import net.minecraft.item.ItemPickaxe;
|
||||
import net.minecraft.item.ItemSpade;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.item.ItemSword;
|
||||
import net.minecraft.network.NetServerHandler;
|
||||
import net.minecraft.network.packet.Packet53BlockChange;
|
||||
import net.minecraft.tileentity.TileEntity;
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
import net.minecraft.util.ChatMessageComponent;
|
||||
import net.minecraft.util.DamageSource;
|
||||
import net.minecraft.util.EnumMovingObjectType;
|
||||
import net.minecraft.util.MathHelper;
|
||||
import net.minecraft.util.MovingObjectPosition;
|
||||
import net.minecraft.util.WeightedRandom;
|
||||
import net.minecraft.util.WeightedRandomItem;
|
||||
import net.minecraft.world.EnumGameType;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraftforge.event.Event;
|
||||
import net.minecraftforge.event.ForgeEventFactory;
|
||||
import net.minecraftforge.event.ServerChatEvent;
|
||||
import net.minecraftforge.event.entity.item.ItemTossEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingAttackEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingDeathEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingDropsEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingEvent.LivingJumpEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingFallEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingHurtEvent;
|
||||
import net.minecraftforge.event.entity.living.LivingSetAttackTargetEvent;
|
||||
import net.minecraftforge.event.entity.player.PlayerOpenContainerEvent;
|
||||
import net.minecraftforge.event.world.BlockEvent;
|
||||
|
||||
public class ForgeHooks
|
||||
{
|
||||
static class GrassEntry extends WeightedRandomItem
|
||||
{
|
||||
public final Block block;
|
||||
public final int metadata;
|
||||
public GrassEntry(Block block, int meta, int weight)
|
||||
{
|
||||
super(weight);
|
||||
this.block = block;
|
||||
this.metadata = meta;
|
||||
}
|
||||
}
|
||||
|
||||
static class SeedEntry extends WeightedRandomItem
|
||||
{
|
||||
public final ItemStack seed;
|
||||
public SeedEntry(ItemStack seed, int weight)
|
||||
{
|
||||
super(weight);
|
||||
this.seed = seed;
|
||||
}
|
||||
}
|
||||
static final List<GrassEntry> grassList = new ArrayList<GrassEntry>();
|
||||
static final List<SeedEntry> seedList = new ArrayList<SeedEntry>();
|
||||
|
||||
public static void plantGrass(World world, int x, int y, int z)
|
||||
{
|
||||
GrassEntry grass = (GrassEntry)WeightedRandom.getRandomItem(world.rand, grassList);
|
||||
if (grass == null || grass.block == null || !grass.block.canBlockStay(world, x, y, z))
|
||||
{
|
||||
return;
|
||||
}
|
||||
world.setBlock(x, y, z, grass.block.blockID, grass.metadata, 3);
|
||||
}
|
||||
|
||||
public static ItemStack getGrassSeed(World world)
|
||||
{
|
||||
SeedEntry entry = (SeedEntry)WeightedRandom.getRandomItem(world.rand, seedList);
|
||||
if (entry == null || entry.seed == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return entry.seed.copy();
|
||||
}
|
||||
|
||||
private static boolean toolInit = false;
|
||||
static HashMap<Item, List> toolClasses = new HashMap<Item, List>();
|
||||
static HashMap<List, Integer> toolHarvestLevels = new HashMap<List, Integer>();
|
||||
static HashSet<List> toolEffectiveness = new HashSet<List>();
|
||||
|
||||
public static boolean canHarvestBlock(Block block, EntityPlayer player, int metadata)
|
||||
{
|
||||
if (block.blockMaterial.isToolNotRequired())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
ItemStack stack = player.inventory.getCurrentItem();
|
||||
if (stack == null)
|
||||
{
|
||||
return player.canHarvestBlock(block);
|
||||
}
|
||||
|
||||
List info = toolClasses.get(stack.getItem());
|
||||
if (info == null)
|
||||
{
|
||||
return player.canHarvestBlock(block);
|
||||
}
|
||||
|
||||
Object[] tmp = info.toArray();
|
||||
String toolClass = (String)tmp[0];
|
||||
int harvestLevel = (Integer)tmp[1];
|
||||
|
||||
Integer blockHarvestLevel = toolHarvestLevels.get(Arrays.asList(block, metadata, toolClass));
|
||||
if (blockHarvestLevel == null)
|
||||
{
|
||||
return player.canHarvestBlock(block);
|
||||
}
|
||||
|
||||
if (blockHarvestLevel > harvestLevel)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean canToolHarvestBlock(Block block, int metadata, ItemStack stack)
|
||||
{
|
||||
if (stack == null) return false;
|
||||
List info = toolClasses.get(stack.getItem());
|
||||
if (info == null) return false;
|
||||
|
||||
Object[] tmp = info.toArray();
|
||||
String toolClass = (String)tmp[0];
|
||||
int harvestLevel = (Integer)tmp[1];
|
||||
|
||||
Integer blockHarvestLevel = toolHarvestLevels.get(Arrays.asList(block, metadata, toolClass));
|
||||
return !(blockHarvestLevel == null || blockHarvestLevel > harvestLevel);
|
||||
}
|
||||
|
||||
public static float blockStrength(Block block, EntityPlayer player, World world, int x, int y, int z)
|
||||
{
|
||||
int metadata = world.getBlockMetadata(x, y, z);
|
||||
float hardness = block.getBlockHardness(world, x, y, z);
|
||||
if (hardness < 0.0F)
|
||||
{
|
||||
return 0.0F;
|
||||
}
|
||||
|
||||
if (!canHarvestBlock(block, player, metadata))
|
||||
{
|
||||
float speed = ForgeEventFactory.getBreakSpeed(player, block, metadata, 1.0f);
|
||||
return (speed < 0 ? 0 : speed) / hardness / 100F;
|
||||
}
|
||||
else
|
||||
{
|
||||
return player.getCurrentPlayerStrVsBlock(block, false, metadata) / hardness / 30F;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isToolEffective(ItemStack stack, Block block, int metadata)
|
||||
{
|
||||
List toolClass = toolClasses.get(stack.getItem());
|
||||
return toolClass != null && toolEffectiveness.contains(Arrays.asList(block, metadata, toolClass.get(0)));
|
||||
}
|
||||
|
||||
static void initTools()
|
||||
{
|
||||
if (toolInit)
|
||||
{
|
||||
return;
|
||||
}
|
||||
toolInit = true;
|
||||
|
||||
MinecraftForge.setToolClass(Item.pickaxeWood, "pickaxe", 0);
|
||||
MinecraftForge.setToolClass(Item.pickaxeStone, "pickaxe", 1);
|
||||
MinecraftForge.setToolClass(Item.pickaxeIron, "pickaxe", 2);
|
||||
MinecraftForge.setToolClass(Item.pickaxeGold, "pickaxe", 0);
|
||||
MinecraftForge.setToolClass(Item.pickaxeDiamond, "pickaxe", 3);
|
||||
|
||||
MinecraftForge.setToolClass(Item.axeWood, "axe", 0);
|
||||
MinecraftForge.setToolClass(Item.axeStone, "axe", 1);
|
||||
MinecraftForge.setToolClass(Item.axeIron, "axe", 2);
|
||||
MinecraftForge.setToolClass(Item.axeGold, "axe", 0);
|
||||
MinecraftForge.setToolClass(Item.axeDiamond, "axe", 3);
|
||||
|
||||
MinecraftForge.setToolClass(Item.shovelWood, "shovel", 0);
|
||||
MinecraftForge.setToolClass(Item.shovelStone, "shovel", 1);
|
||||
MinecraftForge.setToolClass(Item.shovelIron, "shovel", 2);
|
||||
MinecraftForge.setToolClass(Item.shovelGold, "shovel", 0);
|
||||
MinecraftForge.setToolClass(Item.shovelDiamond, "shovel", 3);
|
||||
|
||||
for (Block block : ItemPickaxe.blocksEffectiveAgainst)
|
||||
{
|
||||
MinecraftForge.setBlockHarvestLevel(block, "pickaxe", 0);
|
||||
}
|
||||
|
||||
for (Block block : ItemSpade.blocksEffectiveAgainst)
|
||||
{
|
||||
MinecraftForge.setBlockHarvestLevel(block, "shovel", 0);
|
||||
}
|
||||
|
||||
for (Block block : ItemAxe.blocksEffectiveAgainst)
|
||||
{
|
||||
MinecraftForge.setBlockHarvestLevel(block, "axe", 0);
|
||||
}
|
||||
|
||||
MinecraftForge.setBlockHarvestLevel(Block.obsidian, "pickaxe", 3);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.oreEmerald, "pickaxe", 2);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.oreDiamond, "pickaxe", 2);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.blockDiamond, "pickaxe", 2);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.oreGold, "pickaxe", 2);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.blockGold, "pickaxe", 2);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.oreIron, "pickaxe", 1);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.blockIron, "pickaxe", 1);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.oreLapis, "pickaxe", 1);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.blockLapis, "pickaxe", 1);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.oreRedstone, "pickaxe", 2);
|
||||
MinecraftForge.setBlockHarvestLevel(Block.oreRedstoneGlowing, "pickaxe", 2);
|
||||
MinecraftForge.removeBlockEffectiveness(Block.oreRedstone, "pickaxe");
|
||||
MinecraftForge.removeBlockEffectiveness(Block.obsidian, "pickaxe");
|
||||
MinecraftForge.removeBlockEffectiveness(Block.oreRedstoneGlowing, "pickaxe");
|
||||
}
|
||||
|
||||
public static int getTotalArmorValue(EntityPlayer player)
|
||||
{
|
||||
int ret = 0;
|
||||
for (int x = 0; x < player.inventory.armorInventory.length; x++)
|
||||
{
|
||||
ItemStack stack = player.inventory.armorInventory[x];
|
||||
if (stack != null && stack.getItem() instanceof ISpecialArmor)
|
||||
{
|
||||
ret += ((ISpecialArmor)stack.getItem()).getArmorDisplay(player, stack, x);
|
||||
}
|
||||
else if (stack != null && stack.getItem() instanceof ItemArmor)
|
||||
{
|
||||
ret += ((ItemArmor)stack.getItem()).damageReduceAmount;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
static
|
||||
{
|
||||
grassList.add(new GrassEntry(Block.plantYellow, 0, 20));
|
||||
grassList.add(new GrassEntry(Block.plantRed, 0, 10));
|
||||
seedList.add(new SeedEntry(new ItemStack(Item.seeds), 10));
|
||||
initTools();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a player uses 'pick block', calls new Entity and Block hooks.
|
||||
*/
|
||||
public static boolean onPickBlock(MovingObjectPosition target, EntityPlayer player, World world)
|
||||
{
|
||||
ItemStack result = null;
|
||||
boolean isCreative = player.capabilities.isCreativeMode;
|
||||
|
||||
if (target.typeOfHit == EnumMovingObjectType.TILE)
|
||||
{
|
||||
int x = target.blockX;
|
||||
int y = target.blockY;
|
||||
int z = target.blockZ;
|
||||
Block var8 = Block.blocksList[world.getBlockId(x, y, z)];
|
||||
|
||||
if (var8 == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
result = var8.getPickBlock(target, world, x, y, z);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (target.typeOfHit != EnumMovingObjectType.ENTITY || target.entityHit == null || !isCreative)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
result = target.entityHit.getPickedResult(target);
|
||||
}
|
||||
|
||||
if (result == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int x = 0; x < 9; x++)
|
||||
{
|
||||
ItemStack stack = player.inventory.getStackInSlot(x);
|
||||
if (stack != null && stack.isItemEqual(result) && ItemStack.areItemStackTagsEqual(stack, result))
|
||||
{
|
||||
player.inventory.currentItem = x;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isCreative)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int slot = player.inventory.getFirstEmptyStack();
|
||||
if (slot < 0 || slot >= 9)
|
||||
{
|
||||
slot = player.inventory.currentItem;
|
||||
}
|
||||
|
||||
player.inventory.setInventorySlotContents(slot, result);
|
||||
player.inventory.currentItem = slot;
|
||||
return true;
|
||||
}
|
||||
|
||||
//Optifine Helper Functions u.u, these are here specifically for Optifine
|
||||
//Note: When using Optfine, these methods are invoked using reflection, which
|
||||
//incurs a major performance penalty.
|
||||
public static void onLivingSetAttackTarget(EntityLivingBase entity, EntityLivingBase target)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new LivingSetAttackTargetEvent(entity, target));
|
||||
}
|
||||
|
||||
public static boolean onLivingUpdate(EntityLivingBase entity)
|
||||
{
|
||||
return MinecraftForge.EVENT_BUS.post(new LivingUpdateEvent(entity));
|
||||
}
|
||||
|
||||
public static boolean onLivingAttack(EntityLivingBase entity, DamageSource src, float amount)
|
||||
{
|
||||
return MinecraftForge.EVENT_BUS.post(new LivingAttackEvent(entity, src, amount));
|
||||
}
|
||||
|
||||
public static float onLivingHurt(EntityLivingBase entity, DamageSource src, float amount)
|
||||
{
|
||||
LivingHurtEvent event = new LivingHurtEvent(entity, src, amount);
|
||||
return (MinecraftForge.EVENT_BUS.post(event) ? 0 : event.ammount);
|
||||
}
|
||||
|
||||
public static boolean onLivingDeath(EntityLivingBase entity, DamageSource src)
|
||||
{
|
||||
return MinecraftForge.EVENT_BUS.post(new LivingDeathEvent(entity, src));
|
||||
}
|
||||
|
||||
public static boolean onLivingDrops(EntityLivingBase entity, DamageSource source, ArrayList<EntityItem> drops, int lootingLevel, boolean recentlyHit, int specialDropValue)
|
||||
{
|
||||
return MinecraftForge.EVENT_BUS.post(new LivingDropsEvent(entity, source, drops, lootingLevel, recentlyHit, specialDropValue));
|
||||
}
|
||||
|
||||
public static float onLivingFall(EntityLivingBase entity, float distance)
|
||||
{
|
||||
LivingFallEvent event = new LivingFallEvent(entity, distance);
|
||||
return (MinecraftForge.EVENT_BUS.post(event) ? 0.0f : event.distance);
|
||||
}
|
||||
|
||||
public static boolean isLivingOnLadder(Block block, World world, int x, int y, int z, EntityLivingBase entity)
|
||||
{
|
||||
if (!ForgeDummyContainer.fullBoundingBoxLadders)
|
||||
{
|
||||
return block != null && block.isLadder(world, x, y, z, entity);
|
||||
}
|
||||
else
|
||||
{
|
||||
AxisAlignedBB bb = entity.boundingBox;
|
||||
int mX = MathHelper.floor_double(bb.minX);
|
||||
int mY = MathHelper.floor_double(bb.minY);
|
||||
int mZ = MathHelper.floor_double(bb.minZ);
|
||||
for (int y2 = mY; y2 < bb.maxY; y2++)
|
||||
{
|
||||
for (int x2 = mX; x2 < bb.maxX; x2++)
|
||||
{
|
||||
for (int z2 = mZ; z2 < bb.maxZ; z2++)
|
||||
{
|
||||
block = Block.blocksList[world.getBlockId(x2, y2, z2)];
|
||||
if (block != null && block.isLadder(world, x2, y2, z2, entity))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void onLivingJump(EntityLivingBase entity)
|
||||
{
|
||||
MinecraftForge.EVENT_BUS.post(new LivingJumpEvent(entity));
|
||||
}
|
||||
|
||||
public static EntityItem onPlayerTossEvent(EntityPlayer player, ItemStack item)
|
||||
{
|
||||
player.captureDrops = true;
|
||||
EntityItem ret = player.dropPlayerItemWithRandomChoice(item, false);
|
||||
player.capturedDrops.clear();
|
||||
player.captureDrops = false;
|
||||
|
||||
if (ret == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
ItemTossEvent event = new ItemTossEvent(ret, player);
|
||||
if (MinecraftForge.EVENT_BUS.post(event))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
player.joinEntityItemWithWorld(event.entityItem);
|
||||
return event.entityItem;
|
||||
}
|
||||
|
||||
public static float getEnchantPower(World world, int x, int y, int z)
|
||||
{
|
||||
if (world.isAirBlock(x, y, z))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
Block block = Block.blocksList[world.getBlockId(x, y, z)];
|
||||
return (block == null ? 0 : block.getEnchantPowerBonus(world, x, y, z));
|
||||
}
|
||||
|
||||
public static ChatMessageComponent onServerChatEvent(NetServerHandler net, String raw, ChatMessageComponent comp)
|
||||
{
|
||||
ServerChatEvent event = new ServerChatEvent(net.playerEntity, raw, comp);
|
||||
if (MinecraftForge.EVENT_BUS.post(event))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return event.component;
|
||||
}
|
||||
|
||||
public static boolean canInteractWith(EntityPlayer player, Container openContainer)
|
||||
{
|
||||
PlayerOpenContainerEvent event = new PlayerOpenContainerEvent(player, openContainer);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
return event.getResult() == Event.Result.DEFAULT ? event.canInteractWith : event.getResult() == Event.Result.ALLOW ? true : false;
|
||||
}
|
||||
|
||||
public static BlockEvent.BreakEvent onBlockBreakEvent(World world, EnumGameType gameType, EntityPlayerMP entityPlayer, int x, int y, int z)
|
||||
{
|
||||
// Logic from tryHarvestBlock for pre-canceling the event
|
||||
boolean preCancelEvent = false;
|
||||
if (gameType.isAdventure() && !entityPlayer.isCurrentToolAdventureModeExempt(x, y, z))
|
||||
{
|
||||
preCancelEvent = true;
|
||||
}
|
||||
else if (gameType.isCreative() && entityPlayer.getHeldItem() != null && entityPlayer.getHeldItem().getItem() instanceof ItemSword)
|
||||
{
|
||||
preCancelEvent = true;
|
||||
}
|
||||
|
||||
// Tell client the block is gone immediately then process events
|
||||
if (world.getBlockTileEntity(x, y, z) == null)
|
||||
{
|
||||
Packet53BlockChange packet = new Packet53BlockChange(x, y, z, world);
|
||||
packet.type = 0;
|
||||
packet.metadata = 0;
|
||||
entityPlayer.playerNetServerHandler.sendPacketToPlayer(packet);
|
||||
}
|
||||
|
||||
// Post the block break event
|
||||
Block block = Block.blocksList[world.getBlockId(x, y, z)];
|
||||
int blockMetadata = world.getBlockMetadata(x, y, z);
|
||||
BlockEvent.BreakEvent event = new BlockEvent.BreakEvent(x, y, z, world, block, blockMetadata, entityPlayer);
|
||||
event.setCanceled(preCancelEvent);
|
||||
MinecraftForge.EVENT_BUS.post(event);
|
||||
|
||||
// Handle if the event is canceled
|
||||
if (event.isCanceled())
|
||||
{
|
||||
// Let the client know the block still exists
|
||||
entityPlayer.playerNetServerHandler.sendPacketToPlayer(new Packet53BlockChange(x, y, z, world));
|
||||
|
||||
// Update any tile entity data for this block
|
||||
TileEntity tileentity = world.getBlockTileEntity(x, y, z);
|
||||
if (tileentity != null)
|
||||
{
|
||||
entityPlayer.playerNetServerHandler.sendPacketToPlayer(tileentity.getDescriptionPacket());
|
||||
}
|
||||
}
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.item.EntityItem;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraftforge.event.*;
|
||||
import net.minecraftforge.event.entity.*;
|
||||
import net.minecraftforge.event.world.WorldEvent;
|
||||
|
||||
public class ForgeInternalHandler
|
||||
{
|
||||
@ForgeSubscribe(priority = EventPriority.HIGHEST)
|
||||
public void onEntityJoinWorld(EntityJoinWorldEvent event)
|
||||
{
|
||||
if (!event.world.isRemote)
|
||||
{
|
||||
ForgeChunkManager.loadEntity(event.entity);
|
||||
}
|
||||
|
||||
Entity entity = event.entity;
|
||||
if (entity.getClass().equals(EntityItem.class))
|
||||
{
|
||||
ItemStack stack = entity.getDataWatcher().getWatchableObjectItemStack(10);
|
||||
|
||||
if (stack == null)
|
||||
{
|
||||
//entity.setDead();
|
||||
//event.setCanceled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
Item item = stack.getItem();
|
||||
if (item == null)
|
||||
{
|
||||
FMLLog.warning("Attempted to add a EntityItem to the world with a invalid item: ID %d at " +
|
||||
"(%2.2f, %2.2f, %2.2f), this is most likely a config issue between you and the server. Please double check your configs",
|
||||
stack.itemID, entity.posX, entity.posY, entity.posZ);
|
||||
entity.setDead();
|
||||
event.setCanceled(true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (item.hasCustomEntity(stack))
|
||||
{
|
||||
Entity newEntity = item.createEntity(event.world, entity, stack);
|
||||
if (newEntity != null)
|
||||
{
|
||||
entity.setDead();
|
||||
event.setCanceled(true);
|
||||
event.world.spawnEntityInWorld(newEntity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ForgeSubscribe(priority = EventPriority.HIGHEST)
|
||||
public void onDimensionLoad(WorldEvent.Load event)
|
||||
{
|
||||
ForgeChunkManager.loadWorld(event.world);
|
||||
}
|
||||
|
||||
@ForgeSubscribe(priority = EventPriority.HIGHEST)
|
||||
public void onDimensionSave(WorldEvent.Save event)
|
||||
{
|
||||
ForgeChunkManager.saveWorld(event.world);
|
||||
}
|
||||
|
||||
@ForgeSubscribe(priority = EventPriority.HIGHEST)
|
||||
public void onDimensionUnload(WorldEvent.Unload event)
|
||||
{
|
||||
ForgeChunkManager.unloadWorld(event.world);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* This software is provided under the terms of the Minecraft Forge Public
|
||||
* License v1.0.
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
public class ForgeVersion
|
||||
{
|
||||
//This number is incremented every time we remove deprecated code/major API changes, never reset
|
||||
public static final int majorVersion = 9;
|
||||
//This number is incremented every minecraft release, never reset
|
||||
public static final int minorVersion = 11;
|
||||
//This number is incremented every time a interface changes or new major feature is added, and reset every Minecraft version
|
||||
public static final int revisionVersion = 1;
|
||||
//This number is incremented every time Jenkins builds Forge, and never reset. Should always be 0 in the repo code.
|
||||
public static final int buildVersion = 0;
|
||||
|
||||
public static int getMajorVersion()
|
||||
{
|
||||
return majorVersion;
|
||||
}
|
||||
|
||||
public static int getMinorVersion()
|
||||
{
|
||||
return minorVersion;
|
||||
}
|
||||
|
||||
public static int getRevisionVersion()
|
||||
{
|
||||
return revisionVersion;
|
||||
}
|
||||
|
||||
public static int getBuildVersion()
|
||||
{
|
||||
return buildVersion;
|
||||
}
|
||||
|
||||
public static String getVersion()
|
||||
{
|
||||
return String.format("%d.%d.%d.%d", majorVersion, minorVersion, revisionVersion, buildVersion);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
* Allows for custom entity data and logic to be hooked to existing entity classes.
|
||||
*
|
||||
* @author cpw, mithion
|
||||
*
|
||||
*/
|
||||
public interface IExtendedEntityProperties {
|
||||
/**
|
||||
* Called when the entity that this class is attached to is saved.
|
||||
* Any custom entity data that needs saving should be saved here.
|
||||
* @param compound The compound to save to.
|
||||
*/
|
||||
public void saveNBTData(NBTTagCompound compound);
|
||||
|
||||
/**
|
||||
* Called when the entity that this class is attached to is loaded.
|
||||
* In order to hook into this, you will need to subscribe to the EntityConstructing event.
|
||||
* Otherwise, you will need to initialize manually.
|
||||
* @param compound The compound to load from.
|
||||
*/
|
||||
public void loadNBTData(NBTTagCompound compound);
|
||||
|
||||
/**
|
||||
* Used to initialize the extended properties with the entity that this is attached to, as well
|
||||
* as the world object.
|
||||
* Called automatically if you register with the EntityConstructing event.
|
||||
* @param entity The entity that this extended properties is attached to
|
||||
* @param world The world in which the entity exists
|
||||
*/
|
||||
public void init(Entity entity, World world);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.util.AxisAlignedBB;
|
||||
import net.minecraft.entity.Entity;
|
||||
import net.minecraft.entity.item.EntityMinecart;
|
||||
|
||||
/**
|
||||
* This class defines a replacement for the default minecart collision code.
|
||||
* Only one handler can be registered at a time. It it registered with EntityMinecart.registerCollisionHandler().
|
||||
* If you use this, make it a configuration option.
|
||||
* @author CovertJaguar
|
||||
*/
|
||||
public interface IMinecartCollisionHandler
|
||||
{
|
||||
|
||||
/**
|
||||
* This basically replaces the function of the same name in EnityMinecart.
|
||||
* Code in IMinecartHooks.applyEntityCollisionHook is still run.
|
||||
* @param cart The cart that called the collision.
|
||||
* @param other The object it collided with.
|
||||
*/
|
||||
public void onEntityCollision(EntityMinecart cart, Entity other);
|
||||
|
||||
/**
|
||||
* This function replaced the function of the same name in EntityMinecart.
|
||||
* It is used to define whether minecarts collide with specific entities,
|
||||
* for example items.
|
||||
* @param cart The cart for which the collision box was requested.
|
||||
* @param other The entity requesting the collision box.
|
||||
* @return The collision box or null.
|
||||
*/
|
||||
public AxisAlignedBB getCollisionBox(EntityMinecart cart, Entity other);
|
||||
|
||||
/**
|
||||
* This function is used to define the box used for detecting minecart collisions.
|
||||
* It is generally bigger that the normal collision box.
|
||||
* @param cart The cart for which the collision box was requested.
|
||||
* @return The collision box, cannot be null.
|
||||
*/
|
||||
public AxisAlignedBB getMinecartCollisionBox(EntityMinecart cart);
|
||||
|
||||
/**
|
||||
* This function replaces the function of the same name in EntityMinecart.
|
||||
* It defines whether minecarts are solid to the player.
|
||||
* @param cart The cart for which the bounding box was requested.
|
||||
* @return The bounding box or null.
|
||||
*/
|
||||
public AxisAlignedBB getBoundingBox(EntityMinecart cart);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import net.minecraft.world.World;
|
||||
|
||||
public interface IPlantable
|
||||
{
|
||||
public EnumPlantType getPlantType(World world, int x, int y, int z);
|
||||
public int getPlantID(World world, int x, int y, int z);
|
||||
public int getPlantMetadata(World world, int x, int y, int z);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.util.MovingObjectPosition;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
/**
|
||||
*
|
||||
* This allows for mods to create there own Shear-like items
|
||||
* and have them interact with Blocks/Entities without extra work.
|
||||
* Also, if your block/entity supports the Shears, this allows you
|
||||
* to support mod-shears as well.
|
||||
*
|
||||
*/
|
||||
public interface IShearable
|
||||
{
|
||||
/**
|
||||
* Checks if the object is currently shearable
|
||||
* Example: Sheep return false when they have no wool
|
||||
*
|
||||
* @param item The itemstack that is being used, Possible to be null
|
||||
* @param world The current world
|
||||
* @param x The X Position
|
||||
* @param y The Y Position
|
||||
* @param z The Z Position
|
||||
* @return If this is shearable, and onSheared should be called.
|
||||
*/
|
||||
public boolean isShearable(ItemStack item, World world, int x, int y, int z);
|
||||
|
||||
/**
|
||||
* Performs the shear function on this object.
|
||||
* This is called for both client, and server.
|
||||
* The object should perform all actions related to being sheared,
|
||||
* except for dropping of the items.
|
||||
*
|
||||
* Returns a list of items that resulted from the shearing process.
|
||||
*
|
||||
* For entities, they should trust there internal location information
|
||||
* over the values passed into this function.
|
||||
*
|
||||
* @param item The itemstack that is being used, Possible to be null
|
||||
* @param world The current world
|
||||
* @param x The X Position
|
||||
* @param y The Y Position
|
||||
* @param z The Z Position
|
||||
* @param fortune The fortune level of the shears being used
|
||||
* @return A ArrayList containing all items from this shearing. Possible to be null.
|
||||
*/
|
||||
public ArrayList<ItemStack> onSheared(ItemStack item, World world, int x, int y, int z, int fortune);
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* This software is provided under the terms of the Minecraft Forge Public
|
||||
* License v1.0.
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
|
||||
import net.minecraft.util.DamageSource;
|
||||
import net.minecraft.entity.EntityLivingBase;
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.item.ItemArmor;
|
||||
import net.minecraft.item.ItemStack;
|
||||
|
||||
/**
|
||||
* This interface is to be implemented by ItemArmor classes. It will allow to
|
||||
* modify computation of damage and health loss. Computation will be called
|
||||
* before the actual armor computation, which can then be cancelled.
|
||||
*
|
||||
* @see ItemArmor
|
||||
*/
|
||||
public interface ISpecialArmor
|
||||
{
|
||||
/**
|
||||
* Retrieves the modifiers to be used when calculating armor damage.
|
||||
*
|
||||
* Armor will higher priority will have damage applied to them before
|
||||
* lower priority ones. If there are multiple pieces of armor with the
|
||||
* same priority, damage will be distributed between them based on there
|
||||
* absorption ratio.
|
||||
*
|
||||
* @param player The entity wearing the armor.
|
||||
* @param armor The ItemStack of the armor item itself.
|
||||
* @param source The source of the damage, which can be used to alter armor
|
||||
* properties based on the type or source of damage.
|
||||
* @param damage The total damage being applied to the entity
|
||||
* @param slot The armor slot the item is in.
|
||||
* @return A ArmorProperties instance holding information about how the armor effects damage.
|
||||
*/
|
||||
public ArmorProperties getProperties(EntityLivingBase player, ItemStack armor, DamageSource source, double damage, int slot);
|
||||
|
||||
/**
|
||||
* Get the displayed effective armor.
|
||||
*
|
||||
* @param player The player wearing the armor.
|
||||
* @param armor The ItemStack of the armor item itself.
|
||||
* @param slot The armor slot the item is in.
|
||||
* @return The number of armor points for display, 2 per shield.
|
||||
*/
|
||||
public abstract int getArmorDisplay(EntityPlayer player, ItemStack armor, int slot);
|
||||
|
||||
/**
|
||||
* Applies damage to the ItemStack. The mod is responsible for reducing the
|
||||
* item durability and stack size. If the stack is depleted it will be cleaned
|
||||
* up automatically.
|
||||
*
|
||||
* @param entity The entity wearing the armor
|
||||
* @param stack The ItemStack of the armor item itself.
|
||||
* @param source The source of the damage, which can be used to alter armor
|
||||
* properties based on the type or source of damage.
|
||||
* @param damage The amount of damage being applied to the armor
|
||||
* @param slot The armor slot the item is in.
|
||||
*/
|
||||
public abstract void damageArmor(EntityLivingBase entity, ItemStack stack, DamageSource source, int damage, int slot);
|
||||
|
||||
public static class ArmorProperties implements Comparable<ArmorProperties>
|
||||
{
|
||||
public int Priority = 0;
|
||||
public int AbsorbMax = Integer.MAX_VALUE;
|
||||
public double AbsorbRatio = 0;
|
||||
public int Slot = 0;
|
||||
private static final boolean DEBUG = false; //Only enable this if you wish to be spamed with debugging information.
|
||||
//Left it in because I figured it'd be useful for modders developing custom armor.
|
||||
|
||||
public ArmorProperties(int priority, double ratio, int max)
|
||||
{
|
||||
Priority = priority;
|
||||
AbsorbRatio = ratio;
|
||||
AbsorbMax = max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gathers and applies armor reduction to damage being dealt to a entity.
|
||||
*
|
||||
* @param entity The Entity being damage
|
||||
* @param inventory An array of armor items
|
||||
* @param source The damage source type
|
||||
* @param damage The total damage being done
|
||||
* @return The left over damage that has not been absorbed by the armor
|
||||
*/
|
||||
public static float ApplyArmor(EntityLivingBase entity, ItemStack[] inventory, DamageSource source, double damage)
|
||||
{
|
||||
if (DEBUG)
|
||||
{
|
||||
System.out.println("Start: " + damage + " " + (damage * 25));
|
||||
}
|
||||
damage *= 25;
|
||||
ArrayList<ArmorProperties> dmgVals = new ArrayList<ArmorProperties>();
|
||||
for (int x = 0; x < inventory.length; x++)
|
||||
{
|
||||
ItemStack stack = inventory[x];
|
||||
if (stack == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ArmorProperties prop = null;
|
||||
if (stack.getItem() instanceof ISpecialArmor)
|
||||
{
|
||||
ISpecialArmor armor = (ISpecialArmor)stack.getItem();
|
||||
prop = armor.getProperties(entity, stack, source, damage / 25D, x).copy();
|
||||
}
|
||||
else if (stack.getItem() instanceof ItemArmor && !source.isUnblockable())
|
||||
{
|
||||
ItemArmor armor = (ItemArmor)stack.getItem();
|
||||
prop = new ArmorProperties(0, armor.damageReduceAmount / 25D, armor.getMaxDamage() + 1 - stack.getItemDamage());
|
||||
}
|
||||
if (prop != null)
|
||||
{
|
||||
prop.Slot = x;
|
||||
dmgVals.add(prop);
|
||||
}
|
||||
}
|
||||
if (dmgVals.size() > 0)
|
||||
{
|
||||
ArmorProperties[] props = dmgVals.toArray(new ArmorProperties[dmgVals.size()]);
|
||||
StandardizeList(props, damage);
|
||||
int level = props[0].Priority;
|
||||
double ratio = 0;
|
||||
for (ArmorProperties prop : props)
|
||||
{
|
||||
if (level != prop.Priority)
|
||||
{
|
||||
damage -= (damage * ratio);
|
||||
ratio = 0;
|
||||
level = prop.Priority;
|
||||
}
|
||||
ratio += prop.AbsorbRatio;
|
||||
|
||||
double absorb = damage * prop.AbsorbRatio;
|
||||
if (absorb > 0)
|
||||
{
|
||||
ItemStack stack = inventory[prop.Slot];
|
||||
int itemDamage = (int)(absorb / 25D < 1 ? 1 : absorb / 25D);
|
||||
if (stack.getItem() instanceof ISpecialArmor)
|
||||
{
|
||||
((ISpecialArmor)stack.getItem()).damageArmor(entity, stack, source, itemDamage, prop.Slot);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (DEBUG)
|
||||
{
|
||||
System.out.println("Item: " + stack.toString() + " Absorbed: " + (absorb / 25D) + " Damaged: " + itemDamage);
|
||||
}
|
||||
stack.damageItem(itemDamage, entity);
|
||||
}
|
||||
if (stack.stackSize <= 0)
|
||||
{
|
||||
/*if (entity instanceof EntityPlayer)
|
||||
{
|
||||
stack.onItemDestroyedByUse((EntityPlayer)entity);
|
||||
}*/
|
||||
inventory[prop.Slot] = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
damage -= (damage * ratio);
|
||||
}
|
||||
if (DEBUG)
|
||||
{
|
||||
System.out.println("Return: " + (int)(damage / 25.0F) + " " + damage);
|
||||
}
|
||||
return (float)(damage / 25.0F);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts and standardizes the distribution of damage over armor.
|
||||
*
|
||||
* @param armor The armor information
|
||||
* @param damage The total damage being received
|
||||
*/
|
||||
private static void StandardizeList(ArmorProperties[] armor, double damage)
|
||||
{
|
||||
Arrays.sort(armor);
|
||||
|
||||
int start = 0;
|
||||
double total = 0;
|
||||
int priority = armor[0].Priority;
|
||||
int pStart = 0;
|
||||
boolean pChange = false;
|
||||
boolean pFinished = false;
|
||||
|
||||
if (DEBUG)
|
||||
{
|
||||
for (ArmorProperties prop : armor)
|
||||
{
|
||||
System.out.println(prop);
|
||||
}
|
||||
System.out.println("========================");
|
||||
}
|
||||
|
||||
for (int x = 0; x < armor.length; x++)
|
||||
{
|
||||
total += armor[x].AbsorbRatio;
|
||||
if (x == armor.length - 1 || armor[x].Priority != priority)
|
||||
{
|
||||
if (armor[x].Priority != priority)
|
||||
{
|
||||
total -= armor[x].AbsorbRatio;
|
||||
x--;
|
||||
pChange = true;
|
||||
}
|
||||
if (total > 1)
|
||||
{
|
||||
for (int y = start; y <= x; y++)
|
||||
{
|
||||
double newRatio = armor[y].AbsorbRatio / total;
|
||||
if (newRatio * damage > armor[y].AbsorbMax)
|
||||
{
|
||||
armor[y].AbsorbRatio = (double)armor[y].AbsorbMax / damage;
|
||||
total = 0;
|
||||
for (int z = pStart; z <= y; z++)
|
||||
{
|
||||
total += armor[z].AbsorbRatio;
|
||||
}
|
||||
start = y + 1;
|
||||
x = y;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
armor[y].AbsorbRatio = newRatio;
|
||||
pFinished = true;
|
||||
}
|
||||
}
|
||||
if (pChange && pFinished)
|
||||
{
|
||||
damage -= (damage * total);
|
||||
total = 0;
|
||||
start = x + 1;
|
||||
priority = armor[start].Priority;
|
||||
pStart = start;
|
||||
pChange = false;
|
||||
pFinished = false;
|
||||
if (damage <= 0)
|
||||
{
|
||||
for (int y = x + 1; y < armor.length; y++)
|
||||
{
|
||||
armor[y].AbsorbRatio = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int y = start; y <= x; y++)
|
||||
{
|
||||
total -= armor[y].AbsorbRatio;
|
||||
if (damage * armor[y].AbsorbRatio > armor[y].AbsorbMax)
|
||||
{
|
||||
armor[y].AbsorbRatio = (double)armor[y].AbsorbMax / damage;
|
||||
}
|
||||
total += armor[y].AbsorbRatio;
|
||||
}
|
||||
damage -= (damage * total);
|
||||
total = 0;
|
||||
if (x != armor.length - 1)
|
||||
{
|
||||
start = x + 1;
|
||||
priority = armor[start].Priority;
|
||||
pStart = start;
|
||||
pChange = false;
|
||||
if (damage <= 0)
|
||||
{
|
||||
for (int y = x + 1; y < armor.length; y++)
|
||||
{
|
||||
armor[y].AbsorbRatio = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (DEBUG)
|
||||
{
|
||||
for (ArmorProperties prop : armor)
|
||||
{
|
||||
System.out.println(prop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int compareTo(ArmorProperties o)
|
||||
{
|
||||
if (o.Priority != Priority)
|
||||
{
|
||||
return o.Priority - Priority;
|
||||
}
|
||||
double left = ( AbsorbRatio == 0 ? 0 : AbsorbMax * 100.0D / AbsorbRatio);
|
||||
double right = (o.AbsorbRatio == 0 ? 0 : o.AbsorbMax * 100.0D / o.AbsorbRatio);
|
||||
return (int)(left - right);
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return String.format("%d, %d, %f, %d", Priority, AbsorbMax, AbsorbRatio, (AbsorbRatio == 0 ? 0 : (int)(AbsorbMax * 100.0D / AbsorbRatio)));
|
||||
}
|
||||
|
||||
public ArmorProperties copy()
|
||||
{
|
||||
return new ArmorProperties(Priority, AbsorbRatio, AbsorbMax);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.*;
|
||||
|
||||
import cpw.mods.fml.common.FMLCommonHandler;
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
import cpw.mods.fml.common.Mod;
|
||||
import cpw.mods.fml.common.ModContainer;
|
||||
import cpw.mods.fml.relauncher.Side;
|
||||
import cpw.mods.fml.relauncher.SideOnly;
|
||||
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.material.Material;
|
||||
import net.minecraft.client.renderer.texture.IconRegister;
|
||||
import net.minecraft.crash.CrashReport;
|
||||
import net.minecraft.entity.monster.EntityEnderman;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraftforge.common.ForgeHooks.GrassEntry;
|
||||
import net.minecraftforge.common.ForgeHooks.SeedEntry;
|
||||
import net.minecraftforge.event.EventBus;
|
||||
import net.minecraftforge.event.ForgeSubscribe;
|
||||
import net.minecraftforge.event.entity.EntityEvent;
|
||||
import net.minecraftforge.oredict.OreDictionary;
|
||||
|
||||
public class MinecraftForge
|
||||
{
|
||||
/**
|
||||
* The core Forge EventBusses, all events for Forge will be fired on these,
|
||||
* you should use this to register all your listeners.
|
||||
* This replaces every register*Handler() function in the old version of Forge.
|
||||
* TERRAIN_GEN_BUS for terrain gen events
|
||||
* ORE_GEN_BUS for ore gen events
|
||||
* EVENT_BUS for everything else
|
||||
*/
|
||||
public static final EventBus EVENT_BUS = new EventBus();
|
||||
public static final EventBus TERRAIN_GEN_BUS = new EventBus();
|
||||
public static final EventBus ORE_GEN_BUS = new EventBus();
|
||||
|
||||
private static final ForgeInternalHandler INTERNAL_HANDLER = new ForgeInternalHandler();
|
||||
|
||||
|
||||
/** Register a new plant to be planted when bonemeal is used on grass.
|
||||
* @param block The block to place.
|
||||
* @param metadata The metadata to set for the block when being placed.
|
||||
* @param weight The weight of the plant, where red flowers are
|
||||
* 10 and yellow flowers are 20.
|
||||
*/
|
||||
public static void addGrassPlant(Block block, int metadata, int weight)
|
||||
{
|
||||
ForgeHooks.grassList.add(new GrassEntry(block, metadata, weight));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a new seed to be dropped when breaking tall grass.
|
||||
*
|
||||
* @param seed The item to drop as a seed.
|
||||
* @param weight The relative probability of the seeds,
|
||||
* where wheat seeds are 10.
|
||||
*/
|
||||
public static void addGrassSeed(ItemStack seed, int weight)
|
||||
{
|
||||
ForgeHooks.seedList.add(new SeedEntry(seed, weight));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Register a tool as a tool class with a given harvest level.
|
||||
*
|
||||
* @param tool The custom tool to register.
|
||||
* @param toolClass The tool class to register as. The predefined tool
|
||||
* clases are "pickaxe", "shovel", "axe". You can add
|
||||
* others for custom tools.
|
||||
* @param harvestLevel The harvest level of the tool.
|
||||
*/
|
||||
public static void setToolClass(Item tool, String toolClass, int harvestLevel)
|
||||
{
|
||||
ForgeHooks.toolClasses.put(tool, Arrays.asList(toolClass, harvestLevel));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a block to be harvested by a tool class. This is the metadata
|
||||
* sensitive version, use it if your blocks are using metadata variants.
|
||||
* By default, this sets the block class as effective against that type.
|
||||
*
|
||||
* @param block The block to register.
|
||||
* @param metadata The metadata for the block subtype.
|
||||
* @param toolClass The tool class to register as able to remove this block.
|
||||
* You may register the same block multiple times with different tool
|
||||
* classes, if multiple tool types can be used to harvest this block.
|
||||
* @param harvestLevel The minimum tool harvest level required to successfully
|
||||
* harvest the block.
|
||||
* @see MinecraftForge#setToolClass for details on tool classes.
|
||||
*/
|
||||
public static void setBlockHarvestLevel(Block block, int metadata, String toolClass, int harvestLevel)
|
||||
{
|
||||
List key = Arrays.asList(block, metadata, toolClass);
|
||||
ForgeHooks.toolHarvestLevels.put(key, harvestLevel);
|
||||
ForgeHooks.toolEffectiveness.add(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a block effectiveness mapping. Since setBlockHarvestLevel
|
||||
* makes the tool class effective against the block by default, this can be
|
||||
* used to remove that mapping. This will force a block to be harvested at
|
||||
* the same speed regardless of tool quality, while still requiring a given
|
||||
* harvesting level.
|
||||
*
|
||||
* @param block The block to remove effectiveness from.
|
||||
* @param metadata The metadata for the block subtype.
|
||||
* @param toolClass The tool class to remove the effectiveness mapping from.
|
||||
* @see MinecraftForge#setToolClass for details on tool classes.
|
||||
*/
|
||||
public static void removeBlockEffectiveness(Block block, int metadata, String toolClass)
|
||||
{
|
||||
List key = Arrays.asList(block, metadata, toolClass);
|
||||
ForgeHooks.toolEffectiveness.remove(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a block to be harvested by a tool class.
|
||||
* By default, this sets the block class as effective against that type.
|
||||
*
|
||||
* @param block The block to register.
|
||||
* @param toolClass The tool class to register as able to remove this block.
|
||||
* You may register the same block multiple times with different tool
|
||||
* classes, if multiple tool types can be used to harvest this block.
|
||||
* @param harvestLevel The minimum tool harvest level required to successfully
|
||||
* harvest the block.
|
||||
* @see MinecraftForge#setToolClass for details on tool classes.
|
||||
*/
|
||||
public static void setBlockHarvestLevel(Block block, String toolClass, int harvestLevel)
|
||||
{
|
||||
for (int metadata = 0; metadata < 16; metadata++)
|
||||
{
|
||||
List key = Arrays.asList(block, metadata, toolClass);
|
||||
ForgeHooks.toolHarvestLevels.put(key, harvestLevel);
|
||||
ForgeHooks.toolEffectiveness.add(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the block harvest level for a particular tool class.
|
||||
*
|
||||
* @param block The block to check.
|
||||
* @param metadata The metadata for the block subtype.
|
||||
* @param toolClass The tool class to check as able to remove this block.
|
||||
* @see MinecraftForge#setToolClass for details on tool classes.
|
||||
* @return The harvest level or -1 if no mapping exists.
|
||||
*/
|
||||
public static int getBlockHarvestLevel(Block block, int metadata, String toolClass)
|
||||
{
|
||||
ForgeHooks.initTools();
|
||||
List key = Arrays.asList(block, metadata, toolClass);
|
||||
Integer harvestLevel = ForgeHooks.toolHarvestLevels.get(key);
|
||||
return (harvestLevel == null ? -1 : harvestLevel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a block effectiveness mapping. Since setBlockHarvestLevel
|
||||
* makes the tool class effective against the block by default, this can be
|
||||
* used to remove that mapping. This will force a block to be harvested at
|
||||
* the same speed regardless of tool quality, while still requiring a given
|
||||
* harvesting level.
|
||||
*
|
||||
* @param block The block to remove effectiveness from.
|
||||
* @param toolClass The tool class to remove the effectiveness mapping from.
|
||||
* @see MinecraftForge#setToolClass for details on tool classes.
|
||||
*/
|
||||
public static void removeBlockEffectiveness(Block block, String toolClass)
|
||||
{
|
||||
for (int metadata = 0; metadata < 16; metadata++)
|
||||
{
|
||||
List key = Arrays.asList(block, metadata, toolClass);
|
||||
ForgeHooks.toolEffectiveness.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Method invoked by FML before any other mods are loaded.
|
||||
*/
|
||||
public static void initialize()
|
||||
{
|
||||
System.out.printf("MinecraftForge v%s Initialized\n", ForgeVersion.getVersion());
|
||||
FMLLog.info("MinecraftForge v%s Initialized", ForgeVersion.getVersion());
|
||||
|
||||
Block filler = new Block(0, Material.air)
|
||||
{
|
||||
@SideOnly(Side.CLIENT)
|
||||
@Override
|
||||
public void registerIcons(IconRegister register){}
|
||||
};
|
||||
Block.blocksList[0] = null;
|
||||
Block.opaqueCubeLookup[0] = false;
|
||||
Block.lightOpacity[0] = 0;
|
||||
filler.setUnlocalizedName("ForgeFiller");
|
||||
|
||||
for (int x = 256; x < 4096; x++)
|
||||
{
|
||||
if (Item.itemsList[x] != null)
|
||||
{
|
||||
Block.blocksList[x] = filler;
|
||||
}
|
||||
}
|
||||
|
||||
boolean[] temp = new boolean[4096];
|
||||
System.arraycopy(EntityEnderman.carriableBlocks, 0, temp, 0, EntityEnderman.carriableBlocks.length);
|
||||
EntityEnderman.carriableBlocks = temp;
|
||||
|
||||
EVENT_BUS.register(INTERNAL_HANDLER);
|
||||
OreDictionary.getOreName(0);
|
||||
|
||||
//Force these classes to be defined, Should prevent derp error hiding.
|
||||
new CrashReport("ThisIsFake", new Exception("Not real"));
|
||||
}
|
||||
|
||||
public static String getBrandingVersion()
|
||||
{
|
||||
return "Minecraft Forge "+ ForgeVersion.getVersion();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
/**
|
||||
* This software is provided under the terms of the Minecraft Forge Public
|
||||
* License v1.0.
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import net.minecraftforge.common.Property.Type;
|
||||
|
||||
public class Property
|
||||
{
|
||||
public enum Type
|
||||
{
|
||||
STRING,
|
||||
INTEGER,
|
||||
BOOLEAN,
|
||||
DOUBLE;
|
||||
|
||||
private static Type[] values = {STRING, INTEGER, BOOLEAN, DOUBLE};
|
||||
|
||||
public static Type tryParse(char id)
|
||||
{
|
||||
for (int x = 0; x < values.length; x++)
|
||||
{
|
||||
if (values[x].getID() == id)
|
||||
{
|
||||
return values[x];
|
||||
}
|
||||
}
|
||||
|
||||
return STRING;
|
||||
}
|
||||
|
||||
public char getID()
|
||||
{
|
||||
return name().charAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
private String name;
|
||||
private String value;
|
||||
public String comment;
|
||||
private String[] values;
|
||||
|
||||
private final boolean wasRead;
|
||||
private final boolean isList;
|
||||
private final Type type;
|
||||
private boolean changed = false;
|
||||
|
||||
public Property()
|
||||
{
|
||||
wasRead = false;
|
||||
type = null;
|
||||
isList = false;
|
||||
}
|
||||
|
||||
public Property(String name, String value, Type type)
|
||||
{
|
||||
this(name, value, type, false);
|
||||
}
|
||||
|
||||
Property(String name, String value, Type type, boolean read)
|
||||
{
|
||||
setName(name);
|
||||
this.value = value;
|
||||
this.type = type;
|
||||
wasRead = read;
|
||||
isList = false;
|
||||
}
|
||||
|
||||
public Property(String name, String[] values, Type type)
|
||||
{
|
||||
this(name, values, type, false);
|
||||
}
|
||||
|
||||
Property(String name, String[] values, Type type, boolean read)
|
||||
{
|
||||
setName(name);
|
||||
this.type = type;
|
||||
this.values = values;
|
||||
wasRead = read;
|
||||
isList = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value in this property as it's raw string.
|
||||
*
|
||||
* @return current value
|
||||
*/
|
||||
public String getString()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value in this property as an integer,
|
||||
* if the value is not a valid integer, it will return -1.
|
||||
*
|
||||
* @return The value
|
||||
*/
|
||||
public int getInt()
|
||||
{
|
||||
return getInt(-1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value in this property as an integer,
|
||||
* if the value is not a valid integer, it will return the
|
||||
* provided default.
|
||||
*
|
||||
* @param _default The default to provide if the current value is not a valid integer
|
||||
* @return The value
|
||||
*/
|
||||
public int getInt(int _default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Integer.parseInt(value);
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return _default;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current value stored in this property can be converted to an integer.
|
||||
* @return True if the type of the Property is an Integer
|
||||
*/
|
||||
public boolean isIntValue()
|
||||
{
|
||||
try
|
||||
{
|
||||
Integer.parseInt(value);
|
||||
return true;
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value in this property as a boolean,
|
||||
* if the value is not a valid boolean, it will return the
|
||||
* provided default.
|
||||
*
|
||||
* @param _default The default to provide
|
||||
* @return The value as a boolean, or the default
|
||||
*/
|
||||
public boolean getBoolean(boolean _default)
|
||||
{
|
||||
if (isBooleanValue())
|
||||
{
|
||||
return Boolean.parseBoolean(value);
|
||||
}
|
||||
else
|
||||
{
|
||||
return _default;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current value held by this property is a valid boolean value.
|
||||
* @return True if it is a boolean value
|
||||
*/
|
||||
public boolean isBooleanValue()
|
||||
{
|
||||
return ("true".equals(value.toLowerCase()) || "false".equals(value.toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current value held by this property is a valid double value.
|
||||
* @return True if the value can be converted to an double
|
||||
*/
|
||||
public boolean isDoubleValue()
|
||||
{
|
||||
try
|
||||
{
|
||||
Double.parseDouble(value);
|
||||
return true;
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value in this property as a double,
|
||||
* if the value is not a valid double, it will return the
|
||||
* provided default.
|
||||
*
|
||||
* @param _default The default to provide if the current value is not a valid double
|
||||
* @return The value
|
||||
*/
|
||||
public double getDouble(double _default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Double.parseDouble(value);
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return _default;
|
||||
}
|
||||
}
|
||||
|
||||
public String[] getStringList()
|
||||
{
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the integer value of all values that can
|
||||
* be parsed in the list.
|
||||
*
|
||||
* @return Array of length 0 if none of the values could be parsed.
|
||||
*/
|
||||
public int[] getIntList()
|
||||
{
|
||||
ArrayList<Integer> nums = new ArrayList<Integer>();
|
||||
|
||||
for (String value : values)
|
||||
{
|
||||
try
|
||||
{
|
||||
nums.add(Integer.parseInt(value));
|
||||
}
|
||||
catch (NumberFormatException e){}
|
||||
}
|
||||
|
||||
int[] primitives = new int[nums.size()];
|
||||
|
||||
for (int i = 0; i < nums.size(); i++)
|
||||
{
|
||||
primitives[i] = nums.get(i);
|
||||
}
|
||||
|
||||
return primitives;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all of the current values stored in this property can be converted to an integer.
|
||||
* @return True if the type of the Property is an Integer List
|
||||
*/
|
||||
public boolean isIntList()
|
||||
{
|
||||
for (String value : values)
|
||||
{
|
||||
try
|
||||
{
|
||||
Integer.parseInt(value);
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the boolean value of all values that can
|
||||
* be parsed in the list.
|
||||
*
|
||||
* @return Array of length 0 if none of the values could be parsed.
|
||||
*/
|
||||
public boolean[] getBooleanList()
|
||||
{
|
||||
ArrayList<Boolean> tmp = new ArrayList<Boolean>();
|
||||
for (String value : values)
|
||||
{
|
||||
try
|
||||
{
|
||||
tmp.add(Boolean.parseBoolean(value));
|
||||
}
|
||||
catch (NumberFormatException e){}
|
||||
}
|
||||
|
||||
boolean[] primitives = new boolean[tmp.size()];
|
||||
|
||||
for (int i = 0; i < tmp.size(); i++)
|
||||
{
|
||||
primitives[i] = tmp.get(i);
|
||||
}
|
||||
|
||||
return primitives;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all of current values stored in this property can be converted to a boolean.
|
||||
* @return True if it is a boolean value
|
||||
*/
|
||||
public boolean isBooleanList()
|
||||
{
|
||||
for (String value : values)
|
||||
{
|
||||
if (!"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the double value of all values that can
|
||||
* be parsed in the list.
|
||||
*
|
||||
* @return Array of length 0 if none of the values could be parsed.
|
||||
*/
|
||||
public double[] getDoubleList()
|
||||
{
|
||||
ArrayList<Double> tmp = new ArrayList<Double>();
|
||||
for (String value : values)
|
||||
{
|
||||
try
|
||||
{
|
||||
tmp.add(Double.parseDouble(value));
|
||||
}
|
||||
catch (NumberFormatException e) {}
|
||||
}
|
||||
|
||||
double[] primitives = new double[tmp.size()];
|
||||
|
||||
for (int i = 0; i < tmp.size(); i++)
|
||||
{
|
||||
primitives[i] = tmp.get(i);
|
||||
}
|
||||
|
||||
return primitives;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if all of the current values stored in this property can be converted to a double.
|
||||
* @return True if the type of the Property is a double List
|
||||
*/
|
||||
public boolean isDoubleList()
|
||||
{
|
||||
for (String value : values)
|
||||
{
|
||||
try
|
||||
{
|
||||
Double.parseDouble(value);
|
||||
}
|
||||
catch (NumberFormatException e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name)
|
||||
{
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if this config value was just created, or if it was read from the config file.
|
||||
* This is useful for mods who auto-assign there blocks to determine if the ID returned is
|
||||
* a configured one, or a automatically generated one.
|
||||
*
|
||||
* @return True if this property was loaded from the config file with a value
|
||||
*/
|
||||
public boolean wasRead()
|
||||
{
|
||||
return wasRead;
|
||||
}
|
||||
|
||||
public Type getType()
|
||||
{
|
||||
return type;
|
||||
}
|
||||
|
||||
public boolean isList()
|
||||
{
|
||||
return isList;
|
||||
}
|
||||
|
||||
public boolean hasChanged(){ return changed; }
|
||||
void resetChangedState(){ changed = false; }
|
||||
|
||||
public void set(String value)
|
||||
{
|
||||
this.value = value;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
public void set(String[] values)
|
||||
{
|
||||
this.values = values;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
public void set(int value){ set(Integer.toString(value)); }
|
||||
public void set(boolean value){ set(Boolean.toString(value)); }
|
||||
public void set(double value){ set(Double.toString(value)); }
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import com.google.common.collect.BiMap;
|
||||
import com.google.common.collect.HashBiMap;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.BlockAnvil;
|
||||
import net.minecraft.block.BlockBed;
|
||||
import net.minecraft.block.BlockButton;
|
||||
import net.minecraft.block.BlockChest;
|
||||
import net.minecraft.block.BlockCocoa;
|
||||
import net.minecraft.block.BlockComparator;
|
||||
import net.minecraft.block.BlockDetectorRail;
|
||||
import net.minecraft.block.BlockDispenser;
|
||||
import net.minecraft.block.BlockDoor;
|
||||
import net.minecraft.block.BlockEndPortalFrame;
|
||||
import net.minecraft.block.BlockEnderChest;
|
||||
import net.minecraft.block.BlockFenceGate;
|
||||
import net.minecraft.block.BlockFurnace;
|
||||
import net.minecraft.block.BlockHopper;
|
||||
import net.minecraft.block.BlockLadder;
|
||||
import net.minecraft.block.BlockLever;
|
||||
import net.minecraft.block.BlockLog;
|
||||
import net.minecraft.block.BlockMushroomCap;
|
||||
import net.minecraft.block.BlockPistonBase;
|
||||
import net.minecraft.block.BlockPistonExtension;
|
||||
import net.minecraft.block.BlockPumpkin;
|
||||
import net.minecraft.block.BlockRail;
|
||||
import net.minecraft.block.BlockRailPowered;
|
||||
import net.minecraft.block.BlockRedstoneRepeater;
|
||||
import net.minecraft.block.BlockSkull;
|
||||
import net.minecraft.block.BlockStairs;
|
||||
import net.minecraft.block.BlockTorch;
|
||||
import net.minecraft.block.BlockTrapDoor;
|
||||
import net.minecraft.block.BlockTripWireSource;
|
||||
import net.minecraft.block.BlockVine;
|
||||
import net.minecraft.world.World;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static net.minecraftforge.common.ForgeDirection.*;
|
||||
|
||||
public class RotationHelper {
|
||||
/**
|
||||
* Some blocks have the same rotation.
|
||||
* The first of these blocks (sorted by itemID) should be listed as a type.
|
||||
* Some of the types aren't actual blocks (helper types).
|
||||
*/
|
||||
private static enum BlockType {
|
||||
LOG,
|
||||
DISPENSER,
|
||||
BED,
|
||||
RAIL,
|
||||
RAIL_POWERED,
|
||||
RAIL_ASCENDING,
|
||||
RAIL_CORNER,
|
||||
TORCH,
|
||||
STAIR,
|
||||
CHEST,
|
||||
SIGNPOST,
|
||||
DOOR,
|
||||
LEVER,
|
||||
BUTTON,
|
||||
REDSTONE_REPEATER,
|
||||
TRAPDOOR,
|
||||
MUSHROOM_CAP,
|
||||
MUSHROOM_CAP_CORNER,
|
||||
MUSHROOM_CAP_SIDE,
|
||||
VINE,
|
||||
SKULL,
|
||||
ANVIL
|
||||
}
|
||||
|
||||
private static final ForgeDirection[] UP_DOWN_AXES = new ForgeDirection[] { UP, DOWN };
|
||||
private static final Map<BlockType, BiMap<Integer, ForgeDirection>> MAPPINGS = new HashMap<BlockType, BiMap<Integer, ForgeDirection>>();
|
||||
|
||||
public static ForgeDirection[] getValidVanillaBlockRotations(Block block)
|
||||
{
|
||||
return (block instanceof BlockBed || block instanceof BlockPumpkin || block instanceof BlockFenceGate || block instanceof BlockEndPortalFrame || block instanceof BlockTripWireSource || block instanceof BlockCocoa || block instanceof BlockRailPowered || block instanceof BlockDetectorRail || block instanceof BlockStairs || block instanceof BlockChest || block instanceof BlockEnderChest || block instanceof BlockFurnace || block instanceof BlockLadder || block.blockID == Block.signWall.blockID || block.blockID == Block.signPost.blockID || block instanceof BlockDoor || block instanceof BlockRail || block instanceof BlockButton || block instanceof BlockRedstoneRepeater || block instanceof BlockComparator || block instanceof BlockTrapDoor || block instanceof BlockMushroomCap || block instanceof BlockVine || block instanceof BlockSkull || block instanceof BlockAnvil) ? UP_DOWN_AXES : VALID_DIRECTIONS;
|
||||
}
|
||||
|
||||
public static boolean rotateVanillaBlock(Block block, World worldObj, int x, int y, int z, ForgeDirection axis)
|
||||
{
|
||||
if (worldObj.isRemote)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (axis == UP || axis == DOWN)
|
||||
{
|
||||
if (block instanceof BlockBed || block instanceof BlockPumpkin || block instanceof BlockFenceGate || block instanceof BlockEndPortalFrame || block instanceof BlockTripWireSource || block instanceof BlockCocoa)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x3, BlockType.BED);
|
||||
}
|
||||
if (block instanceof BlockRail)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0xF, BlockType.RAIL);
|
||||
}
|
||||
if (block instanceof BlockRailPowered || block instanceof BlockDetectorRail)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x7, BlockType.RAIL_POWERED);
|
||||
}
|
||||
if (block instanceof BlockStairs)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x3, BlockType.STAIR);
|
||||
}
|
||||
if (block instanceof BlockChest || block instanceof BlockEnderChest || block instanceof BlockFurnace || block instanceof BlockLadder || block.blockID == Block.signWall.blockID)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x7, BlockType.CHEST);
|
||||
}
|
||||
if (block.blockID == Block.signPost.blockID)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0xF, BlockType.SIGNPOST);
|
||||
}
|
||||
if (block instanceof BlockDoor)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x3, BlockType.DOOR);
|
||||
}
|
||||
if (block instanceof BlockButton)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x7, BlockType.BUTTON);
|
||||
}
|
||||
if (block instanceof BlockRedstoneRepeater || block instanceof BlockComparator)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x3, BlockType.REDSTONE_REPEATER);
|
||||
}
|
||||
if (block instanceof BlockTrapDoor)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x3, BlockType.TRAPDOOR);
|
||||
}
|
||||
if (block instanceof BlockMushroomCap)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0xF, BlockType.MUSHROOM_CAP);
|
||||
}
|
||||
if (block instanceof BlockVine)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0xF, BlockType.VINE);
|
||||
}
|
||||
if (block instanceof BlockSkull)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x7, BlockType.SKULL);
|
||||
}
|
||||
if (block instanceof BlockAnvil)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x1, BlockType.ANVIL);
|
||||
}
|
||||
}
|
||||
|
||||
if (block instanceof BlockLog)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0xC, BlockType.LOG);
|
||||
}
|
||||
if (block instanceof BlockDispenser || block instanceof BlockPistonBase || block instanceof BlockPistonExtension || block instanceof BlockHopper)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x7, BlockType.DISPENSER);
|
||||
}
|
||||
if (block instanceof BlockTorch)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0xF, BlockType.TORCH);
|
||||
}
|
||||
if (block instanceof BlockLever)
|
||||
{
|
||||
return rotateBlock(worldObj, x, y, z, axis, 0x7, BlockType.LEVER);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean rotateBlock(World worldObj, int x, int y, int z, ForgeDirection axis, int mask, BlockType blockType)
|
||||
{
|
||||
int rotMeta = worldObj.getBlockMetadata(x, y, z);
|
||||
if (blockType == BlockType.DOOR && (rotMeta & 0x8) == 0x8)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
int masked = rotMeta & ~mask;
|
||||
int meta = rotateMetadata(axis, blockType, rotMeta & mask);
|
||||
if (meta == -1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
worldObj.setBlockMetadataWithNotify(x, y, z, meta & mask | masked, 3);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int rotateMetadata(ForgeDirection axis, BlockType blockType, int meta)
|
||||
{
|
||||
if (blockType == BlockType.RAIL || blockType == BlockType.RAIL_POWERED)
|
||||
{
|
||||
if (meta == 0x0 || meta == 0x1)
|
||||
{
|
||||
return ~meta & 0x1;
|
||||
}
|
||||
if (meta >= 0x2 && meta <= 0x5)
|
||||
{
|
||||
blockType = BlockType.RAIL_ASCENDING;
|
||||
}
|
||||
if (meta >= 0x6 && meta <= 0x9 && blockType == BlockType.RAIL)
|
||||
{
|
||||
blockType = BlockType.RAIL_CORNER;
|
||||
}
|
||||
}
|
||||
if (blockType == BlockType.SIGNPOST)
|
||||
{
|
||||
return (axis == UP) ? (meta + 0x4) % 0x10 : (meta + 0xC) % 0x10;
|
||||
}
|
||||
if (blockType == BlockType.LEVER && (axis == UP || axis == DOWN))
|
||||
{
|
||||
switch (meta)
|
||||
{
|
||||
case 0x5:
|
||||
return 0x6;
|
||||
case 0x6:
|
||||
return 0x5;
|
||||
case 0x7:
|
||||
return 0x0;
|
||||
case 0x0:
|
||||
return 0x7;
|
||||
}
|
||||
}
|
||||
if (blockType == BlockType.MUSHROOM_CAP)
|
||||
{
|
||||
if (meta % 0x2 == 0)
|
||||
{
|
||||
blockType = BlockType.MUSHROOM_CAP_SIDE;
|
||||
}
|
||||
else
|
||||
{
|
||||
blockType = BlockType.MUSHROOM_CAP_CORNER;
|
||||
}
|
||||
}
|
||||
if (blockType == BlockType.VINE)
|
||||
{
|
||||
return ((meta << 1) | ((meta & 0x8) >> 3));
|
||||
}
|
||||
|
||||
ForgeDirection orientation = metadataToDirection(blockType, meta);
|
||||
ForgeDirection rotated = orientation.getRotation(axis);
|
||||
return directionToMetadata(blockType, rotated);
|
||||
}
|
||||
|
||||
private static ForgeDirection metadataToDirection(BlockType blockType, int meta)
|
||||
{
|
||||
if (blockType == BlockType.LEVER)
|
||||
{
|
||||
if (meta == 0x6)
|
||||
{
|
||||
meta = 0x5;
|
||||
}
|
||||
else if (meta == 0x0)
|
||||
{
|
||||
meta = 0x7;
|
||||
}
|
||||
}
|
||||
|
||||
if (MAPPINGS.containsKey(blockType))
|
||||
{
|
||||
BiMap<Integer, ForgeDirection> biMap = MAPPINGS.get(blockType);
|
||||
if (biMap.containsKey(meta))
|
||||
{
|
||||
return biMap.get(meta);
|
||||
}
|
||||
}
|
||||
|
||||
if (blockType == BlockType.TORCH)
|
||||
{
|
||||
return ForgeDirection.getOrientation(6 - meta);
|
||||
}
|
||||
if (blockType == BlockType.STAIR)
|
||||
{
|
||||
return ForgeDirection.getOrientation(5 - meta);
|
||||
}
|
||||
if (blockType == BlockType.CHEST || blockType == BlockType.DISPENSER || blockType == BlockType.SKULL)
|
||||
{
|
||||
return ForgeDirection.getOrientation(meta);
|
||||
}
|
||||
if (blockType == BlockType.BUTTON)
|
||||
{
|
||||
return ForgeDirection.getOrientation(6 - meta);
|
||||
}
|
||||
if (blockType == BlockType.TRAPDOOR)
|
||||
{
|
||||
return ForgeDirection.getOrientation(meta + 2).getOpposite();
|
||||
}
|
||||
|
||||
return ForgeDirection.UNKNOWN;
|
||||
}
|
||||
|
||||
private static int directionToMetadata(BlockType blockType, ForgeDirection direction)
|
||||
{
|
||||
if ((blockType == BlockType.LOG || blockType == BlockType.ANVIL) && (direction.offsetX + direction.offsetY + direction.offsetZ) < 0)
|
||||
{
|
||||
direction = direction.getOpposite();
|
||||
}
|
||||
|
||||
if (MAPPINGS.containsKey(blockType))
|
||||
{
|
||||
BiMap<ForgeDirection, Integer> biMap = MAPPINGS.get(blockType).inverse();
|
||||
if (biMap.containsKey(direction))
|
||||
{
|
||||
return biMap.get(direction);
|
||||
}
|
||||
}
|
||||
|
||||
if (blockType == BlockType.TORCH)
|
||||
{
|
||||
if (direction.ordinal() >= 1)
|
||||
{
|
||||
return 6 - direction.ordinal();
|
||||
}
|
||||
}
|
||||
if (blockType == BlockType.STAIR)
|
||||
{
|
||||
return 5 - direction.ordinal();
|
||||
}
|
||||
if (blockType == BlockType.CHEST || blockType == BlockType.DISPENSER || blockType == BlockType.SKULL)
|
||||
{
|
||||
return direction.ordinal();
|
||||
}
|
||||
if (blockType == BlockType.BUTTON)
|
||||
{
|
||||
if (direction.ordinal() >= 2)
|
||||
{
|
||||
return 6 - direction.ordinal();
|
||||
}
|
||||
}
|
||||
if (blockType == BlockType.TRAPDOOR)
|
||||
{
|
||||
return direction.getOpposite().ordinal() - 2;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
static
|
||||
{
|
||||
BiMap<Integer, ForgeDirection> biMap;
|
||||
|
||||
biMap = HashBiMap.create(3);
|
||||
biMap.put(0x0, UP);
|
||||
biMap.put(0x4, EAST);
|
||||
biMap.put(0x8, SOUTH);
|
||||
MAPPINGS.put(BlockType.LOG, biMap);
|
||||
|
||||
biMap = HashBiMap.create(4);
|
||||
biMap.put(0x0, SOUTH);
|
||||
biMap.put(0x1, WEST);
|
||||
biMap.put(0x2, NORTH);
|
||||
biMap.put(0x3, EAST);
|
||||
MAPPINGS.put(BlockType.BED, biMap);
|
||||
|
||||
biMap = HashBiMap.create(4);
|
||||
biMap.put(0x2, EAST);
|
||||
biMap.put(0x3, WEST);
|
||||
biMap.put(0x4, NORTH);
|
||||
biMap.put(0x5, SOUTH);
|
||||
MAPPINGS.put(BlockType.RAIL_ASCENDING, biMap);
|
||||
|
||||
biMap = HashBiMap.create(4);
|
||||
biMap.put(0x6, WEST);
|
||||
biMap.put(0x7, NORTH);
|
||||
biMap.put(0x8, EAST);
|
||||
biMap.put(0x9, SOUTH);
|
||||
MAPPINGS.put(BlockType.RAIL_CORNER, biMap);
|
||||
|
||||
biMap = HashBiMap.create(6);
|
||||
biMap.put(0x1, EAST);
|
||||
biMap.put(0x2, WEST);
|
||||
biMap.put(0x3, SOUTH);
|
||||
biMap.put(0x4, NORTH);
|
||||
biMap.put(0x5, UP);
|
||||
biMap.put(0x7, DOWN);
|
||||
MAPPINGS.put(BlockType.LEVER, biMap);
|
||||
|
||||
biMap = HashBiMap.create(4);
|
||||
biMap.put(0x0, WEST);
|
||||
biMap.put(0x1, NORTH);
|
||||
biMap.put(0x2, EAST);
|
||||
biMap.put(0x3, SOUTH);
|
||||
MAPPINGS.put(BlockType.DOOR, biMap);
|
||||
|
||||
biMap = HashBiMap.create(4);
|
||||
biMap.put(0x0, NORTH);
|
||||
biMap.put(0x1, EAST);
|
||||
biMap.put(0x2, SOUTH);
|
||||
biMap.put(0x3, WEST);
|
||||
MAPPINGS.put(BlockType.REDSTONE_REPEATER, biMap);
|
||||
|
||||
biMap = HashBiMap.create(4);
|
||||
biMap.put(0x1, EAST);
|
||||
biMap.put(0x3, SOUTH);
|
||||
biMap.put(0x7, NORTH);
|
||||
biMap.put(0x9, WEST);
|
||||
MAPPINGS.put(BlockType.MUSHROOM_CAP_CORNER, biMap);
|
||||
|
||||
biMap = HashBiMap.create(4);
|
||||
biMap.put(0x2, NORTH);
|
||||
biMap.put(0x4, WEST);
|
||||
biMap.put(0x6, EAST);
|
||||
biMap.put(0x8, SOUTH);
|
||||
MAPPINGS.put(BlockType.MUSHROOM_CAP_SIDE, biMap);
|
||||
|
||||
biMap = HashBiMap.create(2);
|
||||
biMap.put(0x0, SOUTH);
|
||||
biMap.put(0x1, EAST);
|
||||
MAPPINGS.put(BlockType.ANVIL, biMap);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package net.minecraftforge.common;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import net.minecraft.world.chunk.storage.IChunkLoader;
|
||||
import net.minecraft.world.storage.IPlayerFileData;
|
||||
import net.minecraft.world.storage.ISaveHandler;
|
||||
import net.minecraft.world.MinecraftException;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
import net.minecraft.world.storage.WorldInfo;
|
||||
import net.minecraft.world.WorldProvider;
|
||||
import net.minecraft.world.WorldServer;
|
||||
|
||||
//Class used internally to provide the world specific data directories.
|
||||
|
||||
public class WorldSpecificSaveHandler implements ISaveHandler
|
||||
{
|
||||
private WorldServer world;
|
||||
private ISaveHandler parent;
|
||||
private File dataDir;
|
||||
|
||||
public WorldSpecificSaveHandler(WorldServer world, ISaveHandler parent)
|
||||
{
|
||||
this.world = world;
|
||||
this.parent = parent;
|
||||
dataDir = new File(world.getChunkSaveLocation(), "data");
|
||||
dataDir.mkdirs();
|
||||
}
|
||||
|
||||
@Override public WorldInfo loadWorldInfo() { return parent.loadWorldInfo(); }
|
||||
@Override public void checkSessionLock() throws MinecraftException { parent.checkSessionLock(); }
|
||||
@Override public IChunkLoader getChunkLoader(WorldProvider 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); }
|
||||
@Override public IPlayerFileData getSaveHandler() { return parent.getSaveHandler(); }
|
||||
@Override public void flush() { parent.flush(); }
|
||||
@Override public String getWorldDirectoryName() { return parent.getWorldDirectoryName(); }
|
||||
|
||||
@Override
|
||||
public File getMapFileFromName(String name)
|
||||
{
|
||||
return new File(dataDir, name + ".dat");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package net.minecraftforge.common.network;
|
||||
|
||||
import net.minecraft.network.INetworkManager;
|
||||
import net.minecraft.network.NetLoginHandler;
|
||||
import net.minecraft.network.packet.NetHandler;
|
||||
import net.minecraft.network.packet.Packet1Login;
|
||||
import net.minecraft.network.packet.Packet250CustomPayload;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraftforge.fluids.FluidIdMapPacket;
|
||||
import cpw.mods.fml.common.network.IConnectionHandler;
|
||||
import cpw.mods.fml.common.network.PacketDispatcher;
|
||||
import cpw.mods.fml.common.network.Player;
|
||||
|
||||
public class ForgeConnectionHandler implements IConnectionHandler {
|
||||
|
||||
@Override
|
||||
public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager)
|
||||
{
|
||||
Packet250CustomPayload[] fluidPackets = ForgePacket.makePacketSet(new FluidIdMapPacket());
|
||||
for (int i = 0; i < fluidPackets.length; i++) {
|
||||
PacketDispatcher.sendPacketToPlayer(fluidPackets[i], player);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String connectionReceived(NetLoginHandler netHandler, INetworkManager manager)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionOpened(NetHandler netClientHandler, String server, int port, INetworkManager manager)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionOpened(NetHandler netClientHandler, MinecraftServer server, INetworkManager manager)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionClosed(INetworkManager manager)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clientLoggedIn(NetHandler clientHandler, INetworkManager manager, Packet1Login login)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package net.minecraftforge.common.network;
|
||||
|
||||
import net.minecraftforge.common.ForgeDummyContainer;
|
||||
import cpw.mods.fml.common.network.NetworkMod;
|
||||
import cpw.mods.fml.common.network.NetworkModHandler;
|
||||
|
||||
public class ForgeNetworkHandler extends NetworkModHandler
|
||||
{
|
||||
public ForgeNetworkHandler(ForgeDummyContainer container)
|
||||
{
|
||||
super(container,container.getClass().getAnnotation(NetworkMod.class));
|
||||
configureNetworkMod(container);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean acceptVersion(String version)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package net.minecraftforge.common.network;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.logging.Level;
|
||||
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.network.INetworkManager;
|
||||
import net.minecraft.network.packet.NetHandler;
|
||||
import net.minecraft.network.packet.Packet250CustomPayload;
|
||||
import net.minecraftforge.common.network.packet.DimensionRegisterPacket;
|
||||
import net.minecraftforge.fluids.FluidIdMapPacket;
|
||||
|
||||
import com.google.common.base.Throwables;
|
||||
import com.google.common.collect.MapMaker;
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
import com.google.common.primitives.Bytes;
|
||||
import com.google.common.primitives.Ints;
|
||||
import com.google.common.primitives.UnsignedBytes;
|
||||
|
||||
import cpw.mods.fml.common.FMLLog;
|
||||
import cpw.mods.fml.common.network.FMLNetworkException;
|
||||
|
||||
public abstract class ForgePacket
|
||||
{
|
||||
public static final String CHANNEL_ID = "FORGE";
|
||||
enum Type
|
||||
{
|
||||
/**
|
||||
* Registers a dimension for a provider on client
|
||||
*/
|
||||
REGISTERDIMENSION(DimensionRegisterPacket.class),
|
||||
/**
|
||||
* The Fluid ID map to send to the client
|
||||
*/
|
||||
FLUID_IDMAP(FluidIdMapPacket.class);
|
||||
|
||||
private Class<? extends ForgePacket> packetType;
|
||||
private ConcurrentMap<INetworkManager, ForgePacket> partTracker;
|
||||
|
||||
private Type(Class<? extends ForgePacket> clazz)
|
||||
{
|
||||
this.packetType = clazz;
|
||||
}
|
||||
|
||||
ForgePacket make()
|
||||
{
|
||||
try
|
||||
{
|
||||
return this.packetType.newInstance();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Throwables.propagateIfPossible(e);
|
||||
FMLLog.log(Level.SEVERE, e, "A bizarre critical error occured during packet encoding");
|
||||
throw new FMLNetworkException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private ForgePacket consumePart(INetworkManager network, byte[] data)
|
||||
{
|
||||
if (partTracker == null)
|
||||
{
|
||||
partTracker = new MapMaker().weakKeys().weakValues().makeMap();
|
||||
}
|
||||
if (!partTracker.containsKey(network))
|
||||
{
|
||||
partTracker.put(network, make());
|
||||
}
|
||||
|
||||
ForgePacket pkt = partTracker.get(network);
|
||||
|
||||
ByteArrayDataInput bdi = ByteStreams.newDataInput(data);
|
||||
int chunkIdx = UnsignedBytes.toInt(bdi.readByte());
|
||||
int chunkTotal = UnsignedBytes.toInt(bdi.readByte());
|
||||
int chunkLength = bdi.readInt();
|
||||
|
||||
if (pkt.partials == null)
|
||||
{
|
||||
pkt.partials = new byte[chunkTotal][];
|
||||
}
|
||||
|
||||
pkt.partials[chunkIdx] = new byte[chunkLength];
|
||||
bdi.readFully(pkt.partials[chunkIdx]);
|
||||
for (int i = 0; i < pkt.partials.length; i++)
|
||||
{
|
||||
if (pkt.partials[i] == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return pkt;
|
||||
}
|
||||
}
|
||||
|
||||
private Type type;
|
||||
private byte[][] partials;
|
||||
|
||||
public static Packet250CustomPayload[] makePacketSet(ForgePacket packet)
|
||||
{
|
||||
byte[] packetData = packet.generatePacket();
|
||||
|
||||
if (packetData.length < 32000)
|
||||
{
|
||||
return new Packet250CustomPayload[]
|
||||
{
|
||||
new Packet250CustomPayload(CHANNEL_ID,
|
||||
Bytes.concat(new byte[]
|
||||
{
|
||||
UnsignedBytes.checkedCast(0), //IsMultipart: False
|
||||
UnsignedBytes.checkedCast(packet.getID())
|
||||
},
|
||||
packetData))
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
byte[][] chunks = new byte[packetData.length / 32000 + 1][];
|
||||
for (int i = 0; i < packetData.length / 32000 + 1; i++)
|
||||
{
|
||||
int len = Math.min(32000, packetData.length - i* 32000);
|
||||
chunks[i] = Bytes.concat(new byte[]
|
||||
{
|
||||
UnsignedBytes.checkedCast(1), //IsMultipart: True
|
||||
UnsignedBytes.checkedCast(packet.getID()), //Packet ID
|
||||
UnsignedBytes.checkedCast(i), //Part Number
|
||||
UnsignedBytes.checkedCast(chunks.length), //Total Parts
|
||||
},
|
||||
Ints.toByteArray(len), //Length
|
||||
Arrays.copyOfRange(packetData, i * 32000, len + i * 32000));
|
||||
}
|
||||
|
||||
Packet250CustomPayload[] ret = new Packet250CustomPayload[chunks.length];
|
||||
for (int i = 0; i < chunks.length; i++)
|
||||
{
|
||||
ret[i] = new Packet250CustomPayload(CHANNEL_ID, chunks[i]);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
public static ForgePacket readPacket(INetworkManager network, byte[] payload)
|
||||
{
|
||||
boolean multipart = UnsignedBytes.toInt(payload[0]) == 1;
|
||||
int type = UnsignedBytes.toInt(payload[1]);
|
||||
Type eType = Type.values()[type];
|
||||
byte[] data = Arrays.copyOfRange(payload, 2, payload.length);
|
||||
|
||||
if (multipart)
|
||||
{
|
||||
ForgePacket pkt = eType.consumePart(network, data);
|
||||
if (pkt != null)
|
||||
{
|
||||
return pkt.consumePacket(Bytes.concat(pkt.partials));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
else
|
||||
{
|
||||
return eType.make().consumePacket(data);
|
||||
}
|
||||
}
|
||||
|
||||
public ForgePacket()
|
||||
{
|
||||
for (Type t : Type.values())
|
||||
{
|
||||
if (t.packetType == getClass())
|
||||
{
|
||||
type = t;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (type == null)
|
||||
{
|
||||
throw new RuntimeException("ForgePacket constructor called on ungregistered type.");
|
||||
}
|
||||
}
|
||||
|
||||
public byte getID()
|
||||
{
|
||||
return UnsignedBytes.checkedCast(type.ordinal());
|
||||
}
|
||||
|
||||
public abstract byte[] generatePacket();
|
||||
|
||||
public abstract ForgePacket consumePacket(byte[] data);
|
||||
|
||||
public abstract void execute(INetworkManager network, EntityPlayer player);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package net.minecraftforge.common.network;
|
||||
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.network.INetworkManager;
|
||||
import net.minecraft.network.NetLoginHandler;
|
||||
import net.minecraft.network.packet.Packet250CustomPayload;
|
||||
import cpw.mods.fml.common.network.FMLPacket;
|
||||
import cpw.mods.fml.common.network.IPacketHandler;
|
||||
import cpw.mods.fml.common.network.Player;
|
||||
|
||||
public class ForgePacketHandler implements IPacketHandler {
|
||||
|
||||
@Override
|
||||
public void onPacketData(INetworkManager network, Packet250CustomPayload packet, Player player)
|
||||
{
|
||||
ForgePacket pkt = ForgePacket.readPacket(network, packet.data);
|
||||
// Part of an incomplete multipart packet
|
||||
if (pkt == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
pkt.execute(network, (EntityPlayer)player);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package net.minecraftforge.common.network;
|
||||
|
||||
import net.minecraft.network.packet.NetHandler;
|
||||
import net.minecraft.network.packet.Packet131MapData;
|
||||
import cpw.mods.fml.common.network.ITinyPacketHandler;
|
||||
|
||||
public class ForgeTinyPacketHandler implements ITinyPacketHandler {
|
||||
|
||||
@Override
|
||||
public void handle(NetHandler handler, Packet131MapData mapData)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* This software is provided under the terms of the Minecraft Forge Public
|
||||
* License v1.0.
|
||||
*/
|
||||
|
||||
package net.minecraftforge.common.network.packet;
|
||||
|
||||
import net.minecraft.entity.player.EntityPlayer;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.network.INetworkManager;
|
||||
import net.minecraft.network.packet.NetHandler;
|
||||
import net.minecraftforge.common.DimensionManager;
|
||||
import net.minecraftforge.common.network.ForgePacket;
|
||||
|
||||
import com.google.common.io.ByteArrayDataInput;
|
||||
import com.google.common.io.ByteArrayDataOutput;
|
||||
import com.google.common.io.ByteStreams;
|
||||
|
||||
/**
|
||||
* This class offers the ability for servers to register dimensions on client.
|
||||
*/
|
||||
public class DimensionRegisterPacket extends ForgePacket
|
||||
{
|
||||
|
||||
/** The dimension ID to register on client */
|
||||
public int dimensionId;
|
||||
/** The provider ID to register with dimension on client */
|
||||
public int providerId;
|
||||
|
||||
// nullary constructor required by ForgePacket.make()
|
||||
public DimensionRegisterPacket() {}
|
||||
|
||||
public DimensionRegisterPacket(int dimensionId, int providerId)
|
||||
{
|
||||
this.dimensionId = dimensionId;
|
||||
this.providerId = providerId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] generatePacket()
|
||||
{
|
||||
ByteArrayDataOutput dat = ByteStreams.newDataOutput();
|
||||
dat.writeInt(this.dimensionId);
|
||||
dat.writeInt(this.providerId);
|
||||
return dat.toByteArray();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ForgePacket consumePacket(byte[] data)
|
||||
{
|
||||
ByteArrayDataInput dat = ByteStreams.newDataInput(data);
|
||||
dimensionId = dat.readInt();
|
||||
providerId = dat.readInt();
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(INetworkManager network, EntityPlayer player)
|
||||
{
|
||||
if (!(player instanceof EntityPlayerMP))
|
||||
{
|
||||
if (!DimensionManager.isDimensionRegistered(dimensionId))
|
||||
{
|
||||
DimensionManager.registerDimension(dimensionId, providerId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user