diff --git a/.gitignore b/.gitignore index 9d8ba96..248f529 100644 --- a/.gitignore +++ b/.gitignore @@ -26,4 +26,6 @@ version.properties #eclipse stuffs /*.classpath /*.project -/.settings/ \ No newline at end of file +/.settings/ +/*.launch +/out \ No newline at end of file diff --git a/build.gradle b/build.gradle index 3a7416d..894dae1 100644 --- a/build.gradle +++ b/build.gradle @@ -4,25 +4,27 @@ * Based on TConstruct's master build file * Authors: Sunstrike, ProgWML6 * Help from AbrarSyed - */ +*/ buildscript { repositories { mavenCentral() - mavenLocal() + mavenLocal() + jcenter() maven { - name = 'ForgeFS' - url = 'http://files.minecraftforge.net/maven' + name = "forge" + url = "http://files.minecraftforge.net/maven" } - maven { + maven { name = "sonatype" url = "https://oss.sonatype.org/content/repositories/snapshots/" } } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + classpath 'net.minecraftforge.gradle:ForgeGradle:2.1-SNAPSHOT' } } +apply plugin: 'net.minecraftforge.gradle.forge' repositories { mavenLocal() @@ -30,11 +32,19 @@ repositories { name 'ForgeFS' url 'http://files.minecraftforge.net/maven' } + maven { + name 'CB Maven FS' + url "http://chickenbones.net/maven/" + } + maven { + name 'forge' + url 'http://files.minecraftforge.net/maven' + } } - -apply plugin: 'forge' -group = 'mantle' +group = 'slimeknights.mantle' +sourceCompatibility = 1.7 +targetCompatibility = 1.7 // Define properties file ext.configFile = file "build.properties" @@ -46,8 +56,7 @@ configFile.withReader { project.ext.config = new ConfigSlurper().parse prop } -// sets version to the slimeKnights default version format -// Finds and sets version data +// sets version to the slimeKnights version format task buildInfo { def cmd = "git rev-parse --short HEAD" def proc = cmd.execute() @@ -75,41 +84,52 @@ if (System.getenv().ARTIFACT_VERSION != null) { version = "${config.minecraft_version}-${artifact_version}" minecraft { - version = config.forge_version + "-" + config.minecraft_version + version = config.minecraft_version + "-" + config.forge_version + mappings = config.mappings runDir = 'run' replace '${version}', project.version - mappings = "snapshot_${config.snapshot}" } - -sourceSets { - main { - resources { - srcDir 'resources' - } - java { - srcDir 'src' - } - } +configurations { + shade + compile.extendsFrom shade } + +dependencies { + //compile "codechicken:CodeChickenLib:${config.minecraft_version}-${config.CCLIB_version}:dev" + //compile "codechicken:CodeChickenCore:${config.minecraft_version}-${config.ccc_version}:dev" + //compile "codechicken:NotEnoughItems:${config.minecraft_version}-${config.NEI_version}:dev" + // Configuration + shade "ninja.leaping.configurate:configurate-hocon:${config.configurate_version}" + shade "ninja.leaping.configurate:configurate-gson:${config.configurate_version}" + +} + processResources { inputs.property "version", artifact_version inputs.property "MCversion", config.minecraft_version - - // replace stuff in text files, not binary ones. + // replace stuff in text files, not binary ones. from(sourceSets.main.resources.srcDirs) { include '**/*.info' - // replace version and MCVersion + // replace version and MCVersion expand 'version':artifact_version,'MCversion':config.minecraft_version } - - // copy everything else, thats not text + // copy everything else, thats not text from(sourceSets.main.resources.srcDirs) { exclude '**/*.info' } } +jar { + // Shading + configurations.shade.each { dep -> + from(project.zipTree(dep)){ + exclude 'META-INF', 'META-INF/**' + } + } + +} // because the normal output has been made to be obfuscated task deobfJar(type: Jar) { from sourceSets.main.output @@ -127,9 +147,7 @@ artifacts { } task("uploadJars", dependsOn:"build") { - description = "uploads JARs" - if (project.hasProperty("local_maven")) { apply plugin: 'maven' uploadArchives { @@ -140,4 +158,4 @@ task("uploadJars", dependsOn:"build") { } } } -} \ No newline at end of file +} diff --git a/build.properties b/build.properties index 700eeaa..183280a 100644 --- a/build.properties +++ b/build.properties @@ -1,4 +1,9 @@ -mod_version=0.3.2 -minecraft_version=1.7.10 -forge_version=10.13.4.1448 -snapshot=20140925 +mod_version=0.6 +minecraft_version=1.8.9 +forge_version=11.15.0.1663 +mappings=snapshot_20151212 + +CCLIB_version=1.1.2.133 +ccc_version=1.0.5.36 +NEI_version=1.0.5.104 +configurate_version=2.0 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index b761216..30d399d 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 93b2e6f..9397848 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Wed Jul 02 15:54:47 CDT 2014 +#Mon Sep 14 12:28:28 PDT 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.7-bin.zip diff --git a/gradlew.bat b/gradlew.bat index 8a0b282..aec9973 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/slimeknights/mantle/Mantle.java b/src/main/java/slimeknights/mantle/Mantle.java new file mode 100644 index 0000000..715843b --- /dev/null +++ b/src/main/java/slimeknights/mantle/Mantle.java @@ -0,0 +1,34 @@ +package slimeknights.mantle; + +import net.minecraftforge.fml.common.Mod; +import net.minecraftforge.fml.common.Mod.Instance; +import net.minecraftforge.fml.common.SidedProxy; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import slimeknights.mantle.common.CommonProxy; + +/** + * Mantle + * + * Central mod object for Mantle + * + * @author Sunstrike + */ +@Mod(modid = Mantle.modId, name = Mantle.modName, version = Mantle.modVersion, dependencies = "required-after:Forge@[11.15,)", acceptedMinecraftVersions="[1.8.8,1.8.9]") +public class Mantle { + + public static final String modId = "mantle"; + public static final String modName = "Mantle"; + public static final String modVersion = "${version}"; + public static final Logger logger = LogManager.getLogger("Mantle"); + + /* Instance of this mod, used for grabbing prototype fields */ + @Instance("mantle") + public static Mantle instance; + + /* Proxies for sides, used for graphics processing */ + @SidedProxy(clientSide = "slimeknights.mantle.client.ClientProxy", serverSide = "slimeknights.mantle.common.CommonProxy") + public static CommonProxy proxy; +} diff --git a/src/main/java/slimeknights/mantle/block/BlockInventory.java b/src/main/java/slimeknights/mantle/block/BlockInventory.java new file mode 100644 index 0000000..4c5e173 --- /dev/null +++ b/src/main/java/slimeknights/mantle/block/BlockInventory.java @@ -0,0 +1,91 @@ +package slimeknights.mantle.block; + +import net.minecraft.block.BlockContainer; +import net.minecraft.block.material.Material; +import net.minecraft.block.state.IBlockState; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryHelper; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.util.EnumFacing; +import net.minecraft.world.World; + +import slimeknights.mantle.tileentity.TileInventory; + +// Updated Version of InventoryBlock in Mantle +public abstract class BlockInventory extends BlockContainer { + + protected BlockInventory(Material material) { + super(material); + } + + // inventories usually need a tileEntity + @Override + public boolean hasTileEntity(IBlockState state) { + return true; + } + + @Override + public abstract TileEntity createNewTileEntity(World worldIn, int meta); + + /** + * Called when the block is activated. Return true if a GUI is opened, false if the block has no GUI. + */ + protected abstract boolean openGui(EntityPlayer player, World world, BlockPos pos); + + @Override + public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumFacing side, + float clickX, float clickY, float clickZ) { + if(player.isSneaking()) { + return false; + } + + if(!world.isRemote) { + return this.openGui(player, world, pos); + } + + return true; + } + + + @Override + public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, + ItemStack stack) { + super.onBlockPlacedBy(worldIn, pos, state, placer, stack); + + // set custom name from named stack + if(stack.hasDisplayName()) { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if(tileentity instanceof TileInventory) { + ((TileInventory) tileentity).setCustomName(stack.getDisplayName()); + } + } + } + + public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if(tileentity instanceof TileInventory) { + InventoryHelper.dropInventoryItems(worldIn, pos, (IInventory) tileentity); + worldIn.updateComparatorOutputLevel(pos, this); + } + + super.breakBlock(worldIn, pos, state); + } + + @Override + public int damageDropped(IBlockState state) { + return getMetaFromState(state); + } + + // BlockContainer sets this to -1, which equals invisible + // we need 3 for standard forge rendering + @Override + public int getRenderType() { + return 3; + } +} diff --git a/src/main/java/slimeknights/mantle/block/EnumBlock.java b/src/main/java/slimeknights/mantle/block/EnumBlock.java new file mode 100644 index 0000000..0405870 --- /dev/null +++ b/src/main/java/slimeknights/mantle/block/EnumBlock.java @@ -0,0 +1,78 @@ +package slimeknights.mantle.block; + +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.block.properties.PropertyEnum; +import net.minecraft.block.state.BlockState; +import net.minecraft.block.state.IBlockState; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IStringSerializable; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.List; + +public class EnumBlock & EnumBlock.IEnumMeta & IStringSerializable> extends Block { + public final PropertyEnum prop; + private final E[] values; + + private static PropertyEnum tmp; + + public EnumBlock(Material material, PropertyEnum prop, Class clazz) { + super(preInit(material, prop)); + this.prop = prop; + values = clazz.getEnumConstants(); + } + + @SuppressWarnings("unchecked") + private static Material preInit(Material material, PropertyEnum property) { + tmp=property; + return material; + } + + @SideOnly(Side.CLIENT) + @Override + public void getSubBlocks(Item itemIn, CreativeTabs tab, List list) { + for(E type : values) { + list.add(new ItemStack(this, 1, type.getMeta())); + } + } + + @Override + protected BlockState createBlockState() { + if(prop == null) { + return new BlockState(this, tmp); + } + return new BlockState(this, prop); + } + + @Override + public IBlockState getStateFromMeta(int meta) { + return this.getDefaultState().withProperty(prop, fromMeta(meta)); + } + + @Override + public int getMetaFromState(IBlockState state) { + return ((E) state.getValue(prop)).getMeta(); + } + + @Override + public int damageDropped(IBlockState state) { + return getMetaFromState(state); + } + + protected E fromMeta(int meta) { + if(meta < 0 || meta >= values.length) { + meta = 0; + } + + return values[meta]; + } + + public interface IEnumMeta { + int getMeta(); + } +} + diff --git a/src/main/java/slimeknights/mantle/client/ClientProxy.java b/src/main/java/slimeknights/mantle/client/ClientProxy.java new file mode 100644 index 0000000..fb018d3 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/ClientProxy.java @@ -0,0 +1,6 @@ +package slimeknights.mantle.client; + +import slimeknights.mantle.common.CommonProxy; + +public class ClientProxy extends CommonProxy { +} diff --git a/src/main/java/slimeknights/mantle/client/CreativeTab.java b/src/main/java/slimeknights/mantle/client/CreativeTab.java new file mode 100644 index 0000000..0e56380 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/CreativeTab.java @@ -0,0 +1,43 @@ +package slimeknights.mantle.client; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +public class CreativeTab extends CreativeTabs { + + private ItemStack icon; + + // a vanilla icon in case the other one isn't present + public CreativeTab(String label, ItemStack backupIcon) { + super(label); + + this.icon = backupIcon; + } + + public void setDisplayIcon(ItemStack displayIcon) { + if(displayIcon != null && displayIcon.getItem() != null) { + this.icon = displayIcon; + } + } + + @SideOnly(Side.CLIENT) + @Override + public ItemStack getIconItemStack() { + return icon; + } + + @SideOnly(Side.CLIENT) + @Override + public int getIconItemDamage() { + return icon.getItemDamage(); + } + + @SideOnly(Side.CLIENT) + @Override + public Item getTabIconItem() { + return icon.getItem(); + } +} diff --git a/src/main/java/slimeknights/mantle/client/ModelHelper.java b/src/main/java/slimeknights/mantle/client/ModelHelper.java new file mode 100644 index 0000000..94370b6 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/ModelHelper.java @@ -0,0 +1,159 @@ +package slimeknights.mantle.client; + +import com.google.common.base.Charsets; +import com.google.common.base.Optional; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.reflect.TypeToken; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.IResource; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.client.model.IColoredBakedQuad; +import net.minecraftforge.client.model.IModelPart; +import net.minecraftforge.client.model.IModelState; +import net.minecraftforge.client.model.SimpleModelState; +import net.minecraftforge.client.model.TRSRTransformation; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.lang.reflect.Type; +import java.util.Map; + +import javax.vecmath.Vector3f; + +public class ModelHelper { + + static final Type maptype = new TypeToken>() {}.getType(); + private static final Gson + GSON = + new GsonBuilder().registerTypeAdapter(maptype, ModelTextureDeserializer.INSTANCE).create(); + + public static final Optional DEFAULT_ITEM_STATE; + public static final Optional DEFAULT_TOOL_STATE; + + public static TextureAtlasSprite getTextureFromBlock(Block block, int meta) { + IBlockState state = block.getStateFromMeta(meta); + return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state); + } + + public static TextureAtlasSprite getTextureFromBlockstate(IBlockState state) { + return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state); + } + + public static BakedQuad colorQuad(int color, BakedQuad quad) { + int[] data = quad.getVertexData(); + + int a = (color >> 24); + if(a == 0) { + a = 255; + } + + int c = 0; + c |= ((color >> 16) & 0xFF) << 0; // red + c |= ((color >> 8) & 0xFF) << 8; // green + c |= ((color >> 0) & 0xFF) << 16; // blue + c |= (a & 0xFF) << 24; // alpha + + // update color in the data. all 4 Vertices. + for(int i = 0; i < 4; i++) { + data[i * 7 + 3] = c; + } + + return new IColoredBakedQuad.ColoredBakedQuad(data, -1, quad.getFace()); + } + + public static Map loadTexturesFromJson(ResourceLocation location) throws IOException { + // get the json + IResource + iresource = + Minecraft.getMinecraft().getResourceManager() + .getResource(new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + ".json")); + Reader reader = new InputStreamReader(iresource.getInputStream(), Charsets.UTF_8); + + return GSON.fromJson(reader, maptype); + } + + public static ImmutableList loadTextureListFromJson(ResourceLocation location) throws IOException { + ImmutableList.Builder builder = ImmutableList.builder(); + for(String s : loadTexturesFromJson(location).values()) { + builder.add(new ResourceLocation(s)); + } + + return builder.build(); + } + + public static ResourceLocation getModelLocation(ResourceLocation location) { + return new ResourceLocation(location.getResourceDomain(), "models/" + location.getResourcePath() + ".json"); + } + + static { + { + // equals forge:default-item + TRSRTransformation thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation( + new Vector3f(0, 1f / 16, -3f / 16), + TRSRTransformation.quatFromYXZDegrees(new Vector3f(-90, 0, 0)), + new Vector3f(0.55f, 0.55f, 0.55f), + null)); + TRSRTransformation firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation( + new Vector3f(0, 4f / 16, 2f / 16), + TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)), + new Vector3f(1.7f, 1.7f, 1.7f), + null)); + DEFAULT_ITEM_STATE = Optional.of(new SimpleModelState(ImmutableMap.of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson, ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson))); + } + { + TRSRTransformation thirdperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation( + new Vector3f(0, 1.25f / 16, -3.5f / 16), + TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, 90, -35)), + new Vector3f(0.85f, 0.85f, 0.85f), + null)); + TRSRTransformation firstperson = TRSRTransformation.blockCenterToCorner(new TRSRTransformation( + new Vector3f(0, 4f / 16, 2f / 16), + TRSRTransformation.quatFromYXZDegrees(new Vector3f(0, -135, 25)), + new Vector3f(1.7f, 1.7f, 1.7f), + null)); + DEFAULT_TOOL_STATE = Optional.of(new SimpleModelState(ImmutableMap + .of(ItemCameraTransforms.TransformType.THIRD_PERSON, thirdperson, ItemCameraTransforms.TransformType.FIRST_PERSON, firstperson))); + } + } + + /** + * Deseralizes a json in the format of { "textures": { "foo": "texture",... }} + * Ignores all invalid json + */ + public static class ModelTextureDeserializer implements JsonDeserializer> { + + public static final ModelTextureDeserializer INSTANCE = new ModelTextureDeserializer(); + + private static final Gson GSON = new Gson(); + + @Override + public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + + JsonObject obj = json.getAsJsonObject(); + JsonElement texElem = obj.get("textures"); + + if(texElem == null) { + throw new JsonParseException("Missing textures entry in json"); + } + + return GSON.fromJson(texElem, maptype); + } + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiElement.java b/src/main/java/slimeknights/mantle/client/gui/GuiElement.java new file mode 100644 index 0000000..908aee9 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiElement.java @@ -0,0 +1,78 @@ +package slimeknights.mantle.client.gui; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Represents a GUI element INSIDE the graphics file. + * The coordinates all refer to the coordinates inside the graphics! + */ +@SideOnly(Side.CLIENT) +public class GuiElement { + + // this is totally completely ugly but it's a simple solution that doesn't clutter everything too much >_> + public static int defaultTexW = 256; + public static int defaultTexH = 256; + + public final int x; + public final int y; + public final int w; + public final int h; + + public int texW; + public int texH; + + public GuiElement(int x, int y, int w, int h, int texW, int texH) { + this(x, y, w, h); + setTextureSize(texW, texH); + + defaultTexW = texW; + defaultTexH = texH; + } + + public GuiElement(int x, int y, int w, int h) { + this.x = x; + this.y = y; + this.w = w; + this.h = h; + setTextureSize(defaultTexW, defaultTexH); + } + + public GuiElement setTextureSize(int w, int h) { + texW = w; + texH = h; + + return this; + } + + public GuiElement shift(int xd, int yd) { + return new GuiElement(this.x + xd, this.y + yd, this.w, this.h, this.texW, this.texH); + } + + /** + * Draws the element at the given x/y coordinates + * + * @param xPos X-Coordinate on the screen + * @param yPos Y-Coordinate on the screen + */ + public int draw(int xPos, int yPos) { + GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos, x, y, w, h, texW, texH); + return w; + } + + public static class Builder { + + public int w; + public int h; + + public Builder(int w, int h) { + this.w = w; + this.h = h; + } + + public GuiElement get(int x, int y, int w, int h) { + return new GuiElement(x, y, w, h, this.w, this.h); + } + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java b/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java new file mode 100644 index 0000000..b9a12ca --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiElementScalable.java @@ -0,0 +1,73 @@ +package slimeknights.mantle.client.gui; + +import net.minecraft.client.gui.GuiScreen; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public class GuiElementScalable extends GuiElement { + + public GuiElementScalable(int x, int y, int w, int h, int texW, int texH) { + super(x, y, w, h, texW, texH); + } + + public GuiElementScalable(int x, int y, int w, int h) { + super(x, y, w, h); + } + + public int drawScaledX(int xPos, int yPos, int width) { + for(int i = 0; i < width / w; i++) { + draw(xPos + i * w, yPos); + } + // remainder that doesn't fit total width + int remainder = width % w; + if(remainder > 0) { + GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, h, texW, texH); + } + + return width; + } + + public int drawScaledY(int xPos, int yPos, int height) { + for(int i = 0; i < height / h; i++) { + draw(xPos, yPos + i * h); + } + // remainder that doesn't fit total width + int remainder = height % h; + if(remainder > 0) { + GuiScreen.drawModalRectWithCustomSizedTexture(xPos, yPos + height - remainder, x, y, w, remainder, texW, texH); + } + + return w; + } + + public int drawScaled(int xPos, int yPos, int width, int height) { + // we draw full height row-wise + int full = height / this.h; + for(int i = 0; i < full; i++) { + drawScaledX(xPos, yPos + i * this.h, width); + } + + yPos += full * this.h; + + // and the remainder is drawn manually + int yRest = height % this.h; + // the same as drawScaledX but with the remaining height + for(int i = 0; i < width / w; i++) { + drawScaledY(xPos + i * w, yPos, yRest); + } + // remainder that doesn't fit total width + int remainder = width % w; + if(remainder > 0) { + GuiScreen.drawModalRectWithCustomSizedTexture(xPos + width - remainder, yPos, x, y, remainder, yRest, texW, texH); + } + + return width; + } + + public GuiElementScalable shift(int xd, int yd) { + GuiElementScalable element = new GuiElementScalable(this.x + xd, this.y + yd, this.w, this.h); + element.setTextureSize(this.texW, texH); + return element; + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiModule.java b/src/main/java/slimeknights/mantle/client/gui/GuiModule.java new file mode 100644 index 0000000..21e2e4c --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiModule.java @@ -0,0 +1,133 @@ +package slimeknights.mantle.client.gui; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.io.IOException; +import java.util.List; + +// a sub-gui. Mostly the same as a separate GuiContainer, but doesn't do the calls that affect the game as if this were the only gui +@SideOnly(Side.CLIENT) +public abstract class GuiModule extends GuiContainer { + + protected final GuiMultiModule parent; + + // left or right of the parent + protected final boolean right; + // top or bottom of the parent + protected final boolean bottom; + + public int yOffset = 0; + public int xOffset = 0; + + public GuiModule(GuiMultiModule parent, Container container, boolean right, boolean bottom) { + super(container); + + this.parent = parent; + this.right = right; + this.bottom = bottom; + } + + public int guiRight() { + return guiLeft + xSize; + } + + public int guiBottom() { + return guiTop + ySize; + } + + @Override + public void initGui() { + this.guiLeft = (this.width - this.xSize) / 2; + this.guiTop = (this.height - this.ySize) / 2; + } + + public void updatePosition(int parentX, int parentY, int parentSizeX, int parentSizeY) { + if(right) { + this.guiLeft = parentX + parentSizeX; + } + else { + this.guiLeft = parentX - this.xSize; + } + + if(bottom) { + this.guiTop = parentY + parentSizeY - this.ySize; + } + else { + this.guiTop = parentY; + } + + this.guiLeft += xOffset; + this.guiTop += yOffset; + } + + public boolean shouldDrawSlot(Slot slot) { + return true; + } + + public boolean isMouseInModule(int mouseX, int mouseY) { + return mouseX >= this.guiLeft && mouseX < this.guiRight() && + mouseY >= this.guiTop && mouseY < this.guiBottom(); + } + + public boolean isMouseOverFullSlot(int mouseX, int mouseY) { + for(Slot slot : (List)inventorySlots.inventorySlots) { + if(parent.isMouseOverSlot(slot, mouseX, mouseY) && slot.getHasStack()) { + return true; + } + } + return false; + } + + /* + public void updateDragged(boolean dragSplitting, Set draggedSlots) { + this.dragSplitting = dragSplitting; + this.dragSplittingSlots.clear(); + for(Object o : draggedSlots) { + if(o instanceof SlotWrapper) + this.dragSplittingSlots.add(((SlotWrapper) o).parent); + else + this.dragSplittingSlots.add(o); + } + } + */ + public void handleDrawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { + this.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY); + } + + public void handleDrawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.drawGuiContainerForegroundLayer(mouseX, mouseY); + } + + + /** + * Custom mouse click handling. + * + * @return True to prevent the main container handling the mouseclick + */ + public boolean handleMouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + return false; + } + + /** + * Custom mouse click handling. + * + * @return True to prevent the main container handling the mouseclick + */ + public boolean handleMouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { + return false; + } + + /** + * Custom mouse click handling. + * + * @return True to prevent the main container handling the mouseclick + */ + public boolean handleMouseReleased(int mouseX, int mouseY, int state) { + return false; + } + +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java b/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java new file mode 100644 index 0000000..30ade5e --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiMultiModule.java @@ -0,0 +1,362 @@ +package slimeknights.mantle.client.gui; + +import com.google.common.collect.Lists; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IChatComponent; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.common.Optional; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.List; + +import slimeknights.mantle.Mantle; +import slimeknights.mantle.inventory.ContainerMultiModule; +import slimeknights.mantle.inventory.SlotWrapper; + +@SideOnly(Side.CLIENT) +@Optional.Interface(iface = "codechicken.nei.api.INEIGuiHandler", modid = "NotEnoughItems") +// todo: NEI +public class GuiMultiModule extends GuiContainer { //implements INEIGuiHandler { + + // NEI-stuff >:( + private static Field NEI_Manager; + + static { + try { + NEI_Manager = GuiContainer.class.getDeclaredField("manager"); + } catch(NoSuchFieldException e) { + NEI_Manager = null; + } + } + + protected List modules = Lists.newArrayList(); + + public int cornerX; + public int cornerY; + public int realWidth; + public int realHeight; + + public GuiMultiModule(ContainerMultiModule container) { + super(container); + + realWidth = -1; + realHeight = -1; + } + + protected void addModule(GuiModule module) { + modules.add(module); + } + + @Override + public void initGui() { + if(realWidth > -1) { + // has to be reset before calling initGui so the position is getting retained + xSize = realWidth; + ySize = realHeight; + } + super.initGui(); + + this.cornerX = this.guiLeft; + this.cornerY = this.guiTop; + this.realWidth = xSize; + this.realHeight = ySize; + + for(GuiModule module : modules) { + updateSubmodule(module); + } + + //this.guiLeft = this.guiTop = 0; + //this.xSize = width; + //this.ySize = height; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { + for(GuiModule module : modules) { + module.handleDrawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY); + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + for(GuiModule module : modules) { + // set correct state for the module + GlStateManager.pushMatrix(); + GlStateManager.translate(-this.guiLeft, -this.guiTop, 0.0F); + GlStateManager.translate(module.guiLeft, module.guiTop, 0.0F); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + module.handleDrawGuiContainerForegroundLayer(mouseX, mouseY); + GlStateManager.popMatrix(); + } + + drawContainerName(); + drawPlayerInventoryName(); + } + + protected void drawBackground(ResourceLocation background) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(background); + this.drawTexturedModalRect(cornerX, cornerY, 0, 0, realWidth, realHeight); + } + + protected void drawContainerName() { + ContainerMultiModule multiContainer = (ContainerMultiModule) this.inventorySlots; + IChatComponent localizedName = multiContainer.getInventoryDisplayName(); + if(localizedName != null) { + this.fontRendererObj.drawString(localizedName.getUnformattedText(), 8, 6, 0x404040); + } + } + + protected void drawPlayerInventoryName() { + String localizedName = Minecraft.getMinecraft().thePlayer.inventory.getDisplayName().getUnformattedText(); + this.fontRendererObj.drawString(localizedName, 8, this.ySize - 96 + 2, 0x404040); + } + + @Override + public void setWorldAndResolution(Minecraft mc, int width, int height) { + super.setWorldAndResolution(mc, width, height); + + // workaround for NEIs ASM hax. sigh. + try { + for(GuiModule module : modules) { + module.setWorldAndResolution(mc, width, height); + if(NEI_Manager != null) { + NEI_Manager.set(module, NEI_Manager.get(this)); + } + updateSubmodule(module); + } + } catch(IllegalAccessException e) { + Mantle.logger.error(e); + } + } + + @Override + public void onResize(Minecraft mc, int width, int height) { + super.onResize(mc, width, height); + + for(GuiModule module : modules) { + module.onResize(mc, width, height); + updateSubmodule(module); + } + } + + @Override + public void drawScreen(int mouseX, int mouseY, float partialTicks) { + int oldX = guiLeft; + int oldY = guiTop; + int oldW = xSize; + int oldH = ySize; + + guiLeft = cornerX; + guiTop = cornerY; + xSize = realWidth; + ySize = realHeight; + super.drawScreen(mouseX, mouseY, partialTicks); + guiLeft = oldX; + guiTop = oldY; + xSize = oldW; + ySize = oldH; + } + + + // needed to get the correct slot on clicking + @Override + protected boolean isPointInRegion(int left, int top, int right, int bottom, int pointX, int pointY) { + pointX -= this.cornerX; + pointY -= this.cornerY; + return pointX >= left - 1 && pointX < left + right + 1 && pointY >= top - 1 && pointY < top + bottom + 1; + } + + protected void updateSubmodule(GuiModule module) { + module.updatePosition(this.cornerX, this.cornerY, this.realWidth, this.realHeight); + + if(module.guiLeft < this.guiLeft) { + this.xSize += this.guiLeft - module.guiLeft; + this.guiLeft = module.guiLeft; + } + if(module.guiTop < this.guiTop) { + this.ySize += this.guiTop - module.guiTop; + this.guiTop = module.guiTop; + } + if(module.guiRight() > this.guiLeft + this.xSize) { + xSize = module.guiRight() - this.guiLeft; + } + if(module.guiBottom() > this.guiTop + this.ySize) { + ySize = module.guiBottom() - this.guiTop; + } + } + + @Override + public void drawSlot(Slot slotIn) { + GuiModule module = getModuleForSlot(slotIn.slotNumber); + + if(module != null) { + Slot slot = slotIn; + // unwrap for the call to the module + if(slotIn instanceof SlotWrapper) { + slot = ((SlotWrapper) slotIn).parent; + } + if(!module.shouldDrawSlot(slot)) { + return; + } + } + + // update slot positions + if(slotIn instanceof SlotWrapper) { + slotIn.xDisplayPosition = ((SlotWrapper) slotIn).parent.xDisplayPosition; + slotIn.yDisplayPosition = ((SlotWrapper) slotIn).parent.yDisplayPosition; + } + + super.drawSlot(slotIn); + } + + @Override + public boolean isMouseOverSlot(Slot slotIn, int mouseX, int mouseY) { + GuiModule module = getModuleForSlot(slotIn.slotNumber); + + // mouse inside the module of the slot? + if(module != null) { + Slot slot = slotIn; + // unwrap for the call to the module + if(slotIn instanceof SlotWrapper) { + slot = ((SlotWrapper) slotIn).parent; + } + if(!module.shouldDrawSlot(slot)) { + return false; + } + } + + return super.isMouseOverSlot(slotIn, mouseX, mouseY); + } + + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { + GuiModule module = getModuleForPoint(mouseX, mouseY); + if(module != null) { + if(module.handleMouseClicked(mouseX, mouseY, mouseButton)) { + return; + } + } + super.mouseClicked(mouseX, mouseY, mouseButton); + } + + @Override + protected void mouseClickMove(int mouseX, int mouseY, int clickedMouseButton, long timeSinceLastClick) { + GuiModule module = getModuleForPoint(mouseX, mouseY); + if(module != null) { + if(module.handleMouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick)) { + return; + } + } + + super.mouseClickMove(mouseX, mouseY, clickedMouseButton, timeSinceLastClick); + } + + @Override + protected void mouseReleased(int mouseX, int mouseY, int state) { + GuiModule module = getModuleForPoint(mouseX, mouseY); + if(module != null) { + if(module.handleMouseReleased(mouseX, mouseY, state)) { + return; + } + } + + super.mouseReleased(mouseX, mouseY, state); + } + + protected GuiModule getModuleForPoint(int x, int y) { + for(GuiModule module : modules) { + if(this.isPointInRegion(module.guiLeft, module.guiTop, module.guiRight(), module.guiBottom(), + x + this.cornerX, y + this.cornerY)) { + return module; + } + } + + return null; + } + + protected GuiModule getModuleForSlot(int slotNumber) { + return getModuleForContainer(getContainer().getSlotContainer(slotNumber)); + } + + protected GuiModule getModuleForContainer(Container container) { + for(GuiModule module : modules) { + if(module.inventorySlots == container) { + return module; + } + } + + return null; + } + + protected ContainerMultiModule getContainer() { + return (ContainerMultiModule) inventorySlots; + } + + /* NEI INTEGRATION */ + // todo: NEI +/* + @Override + @Optional.Method(modid = "NotEnoughItems") + public VisiblityData modifyVisiblity(GuiContainer guiContainer, VisiblityData visiblityData) { + int x = LayoutManager.stateButtons[0].x + LayoutManager.stateButtons[0].w; + int x2 = LayoutManager.timeButtons[3].x + LayoutManager.timeButtons[3].w; + int y2 = LayoutManager.heal.y + LayoutManager.heal.h; + + + for(GuiModule module : modules) { + if(x > module.guiLeft) { + visiblityData.showStateButtons = false; + } + if(x2 > module.guiLeft && y2 > module.guiTop) { + visiblityData.showUtilityButtons = false; + } + } + + return visiblityData; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public Iterable getItemSpawnSlots(GuiContainer guiContainer, ItemStack itemStack) { + return null; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public List getInventoryAreas(GuiContainer guiContainer) { + return Collections.EMPTY_LIST; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean handleDragNDrop(GuiContainer guiContainer, int x, int y, ItemStack itemStack, int k) { + return false; + } + + @Override + @Optional.Method(modid = "NotEnoughItems") + public boolean hideItemPanelSlot(GuiContainer guiContainer, int x, int y, int w, int h) { + for(GuiModule module : modules) { + // check if the panel overlaps the module (check totally not stolen from stackoverflow) + if(module.guiLeft < x + w && module.guiRight() > x && + module.guiTop < y + h && module.guiBottom() > y) { + return true; + } + } + + return false; + } + */ +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java b/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java new file mode 100644 index 0000000..7600d74 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiWidget.java @@ -0,0 +1,26 @@ +package slimeknights.mantle.client.gui; + +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +@SideOnly(Side.CLIENT) +public abstract class GuiWidget { + + public int xPos; + public int yPos; + public int height; + public int width; + + public abstract void draw(); + + /** Where the part will be drawn. Upper left corner. */ + public void setPosition(int x, int y) { + this.xPos = x; + this.yPos = y; + } + + public void setSize(int width, int height) { + this.width = width; + this.height = height; + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java new file mode 100644 index 0000000..316fcd8 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetSlider.java @@ -0,0 +1,255 @@ +package slimeknights.mantle.client.gui; + +import net.minecraft.util.MathHelper; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Mouse; + +// a vertical slider! +@SideOnly(Side.CLIENT) +public class GuiWidgetSlider extends GuiWidget { + + // gui info + public final GuiElement slider; + public final GuiElement sliderHighlighted; + public final GuiElement sliderDisabled; + public final GuiElement slideBarTop; + public final GuiElement slideBarBottom; + public final GuiElementScalable slideBar; + + // slider info + protected int minValue; + protected int maxValue; + protected int increment; + + // positioning info + protected int currentValue; + public int sliderOffset; // x-offset of the slider to the left edge of the slideBar + protected boolean enabled; + protected boolean hidden; + + protected boolean isScrolling; + protected boolean isHighlighted; + // where the slider was clicked on the slider itself (not on the bar, on the thing that slides) + private int clickX; + private int clickY; + private boolean clickedBar; // if the bar has already been clicked and not released + + public GuiWidgetSlider(GuiElement slider, GuiElement sliderHighlighted, GuiElement sliderDisabled, GuiElement slideBarTop, GuiElement slideBarBottom, GuiElementScalable slideBar) { + this.slider = slider; + this.sliderHighlighted = sliderHighlighted; + this.sliderDisabled = sliderDisabled; + this.slideBar = slideBar; + this.slideBarTop = slideBarTop; + this.slideBarBottom = slideBarBottom; + + height = slideBar.h; + width = slideBar.w; + currentValue = minValue = 0; + maxValue = slideBar.h; + increment = 1; + + sliderOffset = MathHelper.abs_int(slideBar.w - slider.w) / 2; + + isScrolling = false; + isHighlighted = false; + + enabled = true; + hidden = false; + } + + /** Sets the height of the whole slider and slidebar */ + public void setSize(int height) { + this.height = height; + } + + /** specifies the values that the slider represents */ + public void setSliderParameters(int min, int max, int stepsize) { + this.minValue = min; + this.maxValue = max; + this.increment = stepsize; + + // just in case + setSliderValue(currentValue); + } + + public int getValue() { + return currentValue; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public void enable() { + this.enabled = true; + } + + public void disable() { + this.enabled = false; + } + + public boolean isEnabled() { + return this.enabled; + } + + public void setHidden(boolean hidden) { + this.hidden = hidden; + } + + public void hide() { + this.hidden = true; + } + + public void show() { + this.hidden = false; + } + + public boolean isHidden() { + return this.hidden; + } + + public void draw() { + if(hidden) { + return; + } + + // slidebar background + slideBarTop.draw(xPos, yPos); + slideBar.drawScaledY(xPos, yPos + slideBarTop.h, getUsableSlidebarHeight()); + slideBarBottom.draw(xPos, yPos + height - slideBarBottom.h); + + int x = xPos + sliderOffset; + int y = yPos + getSliderTop(); + + // the slider depending on state + if(enabled) { + if(isScrolling) { + sliderDisabled.draw(x, y); + } + else if(isHighlighted) { + sliderHighlighted.draw(x, y); + } + else { + slider.draw(x, y); + } + } + else { + sliderDisabled.draw(x, y); + } + } + + public void update(int mouseX, int mouseY, boolean useMouseWheel) { + if(!enabled || hidden) { + return; + } + + boolean mouseDown = Mouse.isButtonDown(0); // left mouse button + int wheel = Mouse.getDWheel(); + + if(useMouseWheel) { + if(wheel > 0) { + decrement(); + return; + } + else if(wheel < 0) { + increment(); + return; + } + } + + // relative position inside the widget + int x = mouseX - xPos; + int y = mouseY - yPos; + + // reset click data + if(!mouseDown && clickedBar) { + clickedBar = false; + } + + // button not pressed and scrolling -> stop scrolling + if(!mouseDown && isScrolling) { + isScrolling = false; + } + // button pressed and scrolling -> update position of slider + else if(isScrolling) { + float d = maxValue - minValue; + float val = (float) (y - clickY) / (float) (getUsableSlidebarHeight() - slider.h); + val *= d; + + if(val < (float) increment / 2f) { + // < 1/2 increment + setSliderValue(minValue); + } + else if(val > maxValue - ((float) increment / 2f)) { + // > max-1/2 increment + setSliderValue(maxValue); + } + else { + // in between + setSliderValue((int) (minValue + (float) increment * Math.round(val))); + } + } + // not scrolling yet but possibly inside the slider + else if(x >= 0 && y >= getSliderTop() && + x - sliderOffset <= slider.w && y <= getSliderTop() + slider.h) { + isHighlighted = true; + if(mouseDown) { + isScrolling = true; + clickX = x - sliderOffset; + clickY = y - getSliderTop(); + } + } + // not on the slider but clicked on the bar + else if(mouseDown && !clickedBar && + x >= 0 && y >= 0 && + x <= slideBar.w && y <= height) { + if(y < getSliderTop()) { + decrement(); + } + else { + increment(); + } + + clickedBar = true; + } + else { + isHighlighted = false; + } + } + + public int increment() { + setSliderValue(currentValue + increment); + return currentValue; + } + + public int decrement() { + setSliderValue(currentValue - increment); + return currentValue; + } + + public int setSliderValue(int val) { + if(val > maxValue) { + val = maxValue; + } + else if(val < minValue) { + val = minValue; + } + + currentValue = val; + return currentValue; + } + + private int getSliderTop() { + float d = maxValue - minValue; + d = (float) (currentValue - minValue) / d; + d *= getUsableSlidebarHeight() - slider.h; + + return (int) d + slideBarTop.h; + } + + private int getUsableSlidebarHeight() { + return height - slideBarTop.h - slideBarBottom.h; + } +} diff --git a/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java new file mode 100644 index 0000000..be8c438 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/gui/GuiWidgetTabs.java @@ -0,0 +1,171 @@ +package slimeknights.mantle.client.gui; + +import com.google.common.collect.Lists; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.GlStateManager; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.client.renderer.entity.RenderItem; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import org.lwjgl.input.Mouse; + +import java.util.List; + +@SideOnly(Side.CLIENT) +public class GuiWidgetTabs extends GuiWidget { + + private static final ResourceLocation + creativeInventoryTabs = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png"); + + private final GuiElement[] tabActive = new GuiElement[3]; + private final GuiElement[] tab = new GuiElement[3]; + + // change this if you need different tabs + public ResourceLocation tabsResource = creativeInventoryTabs; + // changes the y-offset of the tab row + public int yOffset = 4; + // space between 2 tabs + public int spacing = 2; + + public int selected; + public int highlighted; + protected List icons = Lists.newArrayList(); + + private final GuiMultiModule parent; + private boolean clicked = false; + + public GuiWidgetTabs(GuiMultiModule parent, GuiElement tabLeft, GuiElement tabCenter, GuiElement tabRight, GuiElement activeLeft, GuiElement activeCenter, GuiElement activeRight) { + this.parent = parent; + + this.tab[0] = tabLeft; + this.tab[1] = tabCenter; + this.tab[2] = tabRight; + this.tabActive[0] = activeLeft; + this.tabActive[1] = activeCenter; + this.tabActive[2] = activeRight; + + selected = 0; + } + + public void addTab(ItemStack icon) { + icons.add(icon); + } + + public void clear() { + selected = 0; + icons.clear(); + } + + public void update(int mouseX, int mouseY) { + boolean mouseDown = Mouse.isButtonDown(0); // left mouse button + + // did we click on a tab? + mouseX -= this.xPos; + mouseY -= this.yPos; + + // update highlighted + highlighted = -1; + if(mouseY >= 0 && mouseY <= tab[1].h) { + // which one did we click? + int x = 0; + for(int i = 0; i < icons.size(); i++) { + // clicking on spacing has no effect + if(mouseX >= x && mouseX < x + tab[1].w) { + highlighted = i; + break; + } + x += tab[1].w; + x += spacing; + } + } + + // already clicked + if(clicked) { + // still clicking + if(mouseDown) { + return; + } + // release click + else { + clicked = false; + return; + } + } + // new click + else if(mouseDown) { + clicked = true; + } + // no click - do nothing + else { + return; + } + + // was new click, select highlighted + if(highlighted > -1) { + selected = highlighted; + } + } + + @Override + public void draw() { + int y = yPos + yOffset; + for(int i = 0; i < icons.size(); i++) { + int x = xPos + i * tab[0].w; + + if(i > 0) { + x += i * spacing; + } + + GuiElement[] toDraw; + if(i == selected) { + toDraw = tabActive; + } + else { + toDraw = tab; + } + + GuiElement actualTab; + if(i == 0 && x == parent.cornerX) { + actualTab = toDraw[0]; + } + else if(x == parent.cornerX + parent.width) { + actualTab = toDraw[2]; + } + else { + actualTab = toDraw[1]; + } + + // todo: draw all the tabs first and then all the itemstacks so it doesn't have to switch texture in between all the time + + // rebind texture from drawing an itemstack + Minecraft.getMinecraft().getTextureManager().bindTexture(tabsResource); + actualTab.draw(x, y); + + + ItemStack icon = icons.get(i); + if(icon != null) { + RenderHelper.enableGUIStandardItemLighting(); + drawItemStack(icon, x + (actualTab.w - 16) / 2, y + (actualTab.h - 16) / 2); + RenderHelper.disableStandardItemLighting(); + //RenderHelper.enableStandardItemLighting(); + } + } + } + + // guiContainer.drawItemStack + private void drawItemStack(ItemStack stack, int x, int y) { + RenderItem itemRender = Minecraft.getMinecraft().getRenderItem(); + GlStateManager.translate(0.0F, 0.0F, 32.0F); + itemRender.zLevel = 200; + //FontRenderer font = stack.getItem().getFontRenderer(stack); + + itemRender.renderItemAndEffectIntoGUI(stack, x, y); + //this.itemRender.renderItemOverlayIntoGUI(font, stack, x, y - (this.draggedStack == null ? 0 : 8), altText); + //this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } +} diff --git a/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java b/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java new file mode 100644 index 0000000..7ec36d9 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/model/BlockItemModelWrapper.java @@ -0,0 +1,88 @@ +package slimeknights.mantle.client.model; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.vertex.VertexFormat; +import net.minecraft.client.resources.model.IBakedModel; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.client.model.IFlexibleBakedModel; +import net.minecraftforge.client.model.IPerspectiveAwareModel; +import net.minecraftforge.client.model.TRSRTransformation; + +import org.apache.commons.lang3.tuple.Pair; + +import java.util.List; + +import javax.vecmath.Matrix4f; +import javax.vecmath.Vector3f; + +/** + * Takes a blockmodel and applies the standard-block-perspective for third_person to it + */ +public class BlockItemModelWrapper implements IPerspectiveAwareModel, IFlexibleBakedModel { + + // copied from the forge variants V1 default-block transform + public static final Matrix4f THIRD_PERSON_BLOCK_TRANSFORM = new TRSRTransformation( + new Vector3f(0, 1.5f / 16, -2.75f / 16), // translation + TRSRTransformation.quatFromYXZDegrees(new Vector3f(10, -45, 170)), // rotation + new Vector3f(0.375f, 0.375f, 0.375f), // scale + null).getMatrix(); + + private final IFlexibleBakedModel parent; + + public BlockItemModelWrapper(IFlexibleBakedModel parent) { + this.parent = parent; + } + + @Override + public Pair handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) { + Matrix4f matrix = null; + // fix transformation in hand + if(cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON) { + matrix = THIRD_PERSON_BLOCK_TRANSFORM; + } + + return Pair.of(this, matrix); + } + + @Override + public List getFaceQuads(EnumFacing p_177551_1_) { + return parent.getFaceQuads(p_177551_1_); + } + + @Override + public List getGeneralQuads() { + return parent.getGeneralQuads(); + } + + @Override + public VertexFormat getFormat() { + return parent.getFormat(); + } + + @Override + public boolean isAmbientOcclusion() { + return false; + } + + @Override + public boolean isGui3d() { + return parent.isGui3d(); + } + + @Override + public boolean isBuiltInRenderer() { + return parent.isBuiltInRenderer(); + } + + @Override + public TextureAtlasSprite getParticleTexture() { + return parent.getParticleTexture(); + } + + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return parent.getItemCameraTransforms(); + } +} diff --git a/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java b/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java new file mode 100644 index 0000000..f32ef74 --- /dev/null +++ b/src/main/java/slimeknights/mantle/client/model/TRSRBakedModel.java @@ -0,0 +1,166 @@ +package slimeknights.mantle.client.model; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; + +import net.minecraft.client.renderer.block.model.BakedQuad; +import net.minecraft.client.renderer.block.model.ItemCameraTransforms; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.renderer.vertex.VertexFormat; +import net.minecraft.client.renderer.vertex.VertexFormatElement; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.client.model.IFlexibleBakedModel; +import net.minecraftforge.client.model.TRSRTransformation; +import net.minecraftforge.client.model.pipeline.UnpackedBakedQuad; +import net.minecraftforge.client.model.pipeline.VertexTransformer; + +import java.util.EnumMap; +import java.util.List; + +import javax.vecmath.Matrix3f; +import javax.vecmath.Matrix4f; +import javax.vecmath.Vector3f; +import javax.vecmath.Vector4f; + +// for those wondering TRSR stands for Translation Rotation Scale Rotation +public class TRSRBakedModel implements IFlexibleBakedModel { + + protected final ImmutableList general; + protected final ImmutableMap> faces; + protected final IFlexibleBakedModel original; + + public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float scale) { + this(original, x, y, z, 0, 0, 0, scale, scale, scale); + } + + public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scale) { + this(original, x, y, z, rotX, rotY, rotZ, scale, scale, scale); + } + + public TRSRBakedModel(IFlexibleBakedModel original, float x, float y, float z, float rotX, float rotY, float rotZ, float scaleX, float scaleY, float scaleZ) { + this(original, new TRSRTransformation(new Vector3f(x, y, z), + null, + new Vector3f(scaleX, scaleY, scaleZ), + TRSRTransformation.quatFromYXZ(rotY, rotX, rotZ))); + } + + public TRSRBakedModel(IFlexibleBakedModel original, TRSRTransformation transform) { + this.original = original; + + ImmutableList.Builder builder; + builder = ImmutableList.builder(); + + transform = TRSRTransformation.blockCenterToCorner(transform); + + // face quads + EnumMap> faces = Maps.newEnumMap(EnumFacing.class); + for(EnumFacing face : EnumFacing.values()) { + if(!original.isBuiltInRenderer()) { + for(BakedQuad quad : original.getFaceQuads(face)) { + Transformer transformer = new Transformer(transform, original.getFormat()); + quad.pipe(transformer); + builder.add(transformer.build()); + } + } + //faces.put(face, builder.build()); + faces.put(face, ImmutableList.of()); + } + + // general quads + //builder = ImmutableList.builder(); + if(!original.isBuiltInRenderer()) { + for(BakedQuad quad : original.getGeneralQuads()) { + Transformer transformer = new Transformer(transform, original.getFormat()); + quad.pipe(transformer); + builder.add(transformer.build()); + } + } + + this.general = builder.build(); + this.faces = Maps.immutableEnumMap(faces); + } + + @Override + public List getFaceQuads(EnumFacing side) { + return faces.get(side); + } + + @Override + public List getGeneralQuads() { + return general; + } + + @Override + public boolean isAmbientOcclusion() { + return false; + } + + @Override + public boolean isGui3d() { + return original.isGui3d(); + } + + @Override + public boolean isBuiltInRenderer() { + return original.isBuiltInRenderer(); + } + + @Override + public TextureAtlasSprite getParticleTexture() { + return original.getParticleTexture(); + } + + @Override + public ItemCameraTransforms getItemCameraTransforms() { + return original.getItemCameraTransforms(); + } + + @Override + public VertexFormat getFormat() { + return original.getFormat(); + } + + public static class Transformer extends VertexTransformer { + + protected Matrix4f transformation; + protected Matrix3f normalTransformation; + + public Transformer(TRSRTransformation transformation, VertexFormat format) { + super(new UnpackedBakedQuad.Builder(format)); + // position transform + this.transformation = transformation.getMatrix(); + // normal transform + this.normalTransformation = new Matrix3f(); + this.transformation.getRotationScale(this.normalTransformation); + this.normalTransformation.invert(); + this.normalTransformation.transpose(); + } + + @Override + public void put(int element, float... data) { + VertexFormatElement.EnumUsage usage = parent.getVertexFormat().getElement(element).getUsage(); + + // transform normals and position + if(usage == VertexFormatElement.EnumUsage.POSITION && data.length >= 3) { + Vector4f vec = new Vector4f(data); + vec.setW(1.0f); + transformation.transform(vec); + data = new float[4]; + vec.get(data); + } + else if(usage == VertexFormatElement.EnumUsage.NORMAL && data.length >= 3) { + Vector3f vec = new Vector3f(data); + normalTransformation.transform(vec); + vec.normalize(); + data = new float[4]; + vec.get(data); + } + super.put(element, data); + } + + public UnpackedBakedQuad build() { + return ((UnpackedBakedQuad.Builder)parent).build(); + } + } +} diff --git a/src/main/java/slimeknights/mantle/common/CommonProxy.java b/src/main/java/slimeknights/mantle/common/CommonProxy.java new file mode 100644 index 0000000..e2dd4a7 --- /dev/null +++ b/src/main/java/slimeknights/mantle/common/CommonProxy.java @@ -0,0 +1,4 @@ +package slimeknights.mantle.common; + +public class CommonProxy { +} diff --git a/src/main/java/slimeknights/mantle/common/GuiHandler.java b/src/main/java/slimeknights/mantle/common/GuiHandler.java new file mode 100644 index 0000000..22bb260 --- /dev/null +++ b/src/main/java/slimeknights/mantle/common/GuiHandler.java @@ -0,0 +1,31 @@ +package slimeknights.mantle.common; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.network.IGuiHandler; + +/** + * A GuiHandler implementation that forwards the container/gui creation to the TEs, eliminating the need for GUI IDs. + */ +public class GuiHandler implements IGuiHandler { + + @Override + public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity te = world.getTileEntity(new BlockPos(x, y, z)); + if(te instanceof IInventoryGui) { + return ((IInventoryGui) te).createContainer(player.inventory, world, new BlockPos(x, y, z)); + } + return null; + } + + @Override + public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { + TileEntity te = world.getTileEntity(new BlockPos(x, y, z)); + if(te instanceof IInventoryGui) { + return ((IInventoryGui) te).createGui(player.inventory, world, new BlockPos(x, y, z)); + } + return null; + } +} diff --git a/src/main/java/slimeknights/mantle/common/IInventoryGui.java b/src/main/java/slimeknights/mantle/common/IInventoryGui.java new file mode 100644 index 0000000..c4cea7d --- /dev/null +++ b/src/main/java/slimeknights/mantle/common/IInventoryGui.java @@ -0,0 +1,20 @@ +package slimeknights.mantle.common; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.util.BlockPos; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Used in conjunction with GuiHandler. Implement in a TE to have it open its GUI/Container. + */ +public interface IInventoryGui { + + Container createContainer(InventoryPlayer inventoryplayer, World world, BlockPos pos); + + @SideOnly(Side.CLIENT) + GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos); +} diff --git a/src/main/java/slimeknights/mantle/inventory/BaseContainer.java b/src/main/java/slimeknights/mantle/inventory/BaseContainer.java new file mode 100644 index 0000000..d2b43b1 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/BaseContainer.java @@ -0,0 +1,301 @@ +package slimeknights.mantle.inventory; + +import com.google.common.collect.Lists; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.util.IChatComponent; +import net.minecraft.world.World; +import net.minecraft.world.WorldServer; + +import java.util.List; + +import slimeknights.mantle.util.SlimeknightException; + +/** Same as Container but provides some extra functionality to simplify things */ +public abstract class BaseContainer extends Container { + + protected double maxDist = 8 * 8; // 8 blocks + protected T tile; + protected final Block originalBlock; // used to check if the block we interacted with got broken + protected final BlockPos pos; + protected final World world; + + public List subContainers = Lists.newArrayList(); + + public BaseContainer(T tile) { + this.tile = tile; + + this.world = tile.getWorld(); + this.pos = tile.getPos(); + this.originalBlock = world.getBlockState(pos).getBlock(); + } + + public void syncOnOpen(EntityPlayerMP playerOpened) { + // find another player that already has the gui for this tile open + WorldServer server = playerOpened.getServerForPlayer(); + for(EntityPlayer player : (List) server.playerEntities) { + if(player == playerOpened) { + continue; + } + if(player.openContainer instanceof BaseContainer) { + if(this.sameGui((BaseContainer) player.openContainer)) { + syncWithOtherContainer((BaseContainer) player.openContainer, playerOpened); + return; + } + } + } + + // no player has a container open for the tile + syncNewContainer(playerOpened); + } + + public T getTile() { + return tile; + } + + /** + * Called when the container is opened and another player already has a container for this tile open + * Sync to the same state here. + */ + protected void syncWithOtherContainer(BaseContainer otherContainer, EntityPlayerMP player) { + } + + /** + * Called when the container is opened and no other player has it open. + * Set the default state here. + */ + protected void syncNewContainer(EntityPlayerMP player) { + } + + public boolean sameGui(BaseContainer otherContainer) { + return this.tile == otherContainer.tile; + } + + @Override + public boolean canInteractWith(EntityPlayer playerIn) { + Block block = world.getBlockState(pos).getBlock(); + // does the block we interacted with still exist? + if(block == Blocks.air || block != originalBlock) { + return false; + } + + // too far away from block? + return playerIn.getDistanceSq((double) pos.getX() + 0.5d, + (double) pos.getY() + 0.5d, + (double) pos.getZ() + 0.5d) <= maxDist; + } + + @SuppressWarnings("unchecked") + public List getInventory() { + return (List) super.getInventory(); + } + + public IChatComponent getInventoryDisplayName() { + if(tile instanceof IInventory) { + return ((IInventory) tile).getDisplayName(); + } + return null; + } + + // standard yOffset calculation for chestlike inventories: + // yOffset = (numRows - 4) * 18; (the -4 because of the 3 rows of inventory + 1 row of hotbar) + + protected int playerInventoryStart = -1; + + /** + * Draws the player inventory starting at the given position + * + * @param playerInventory The players inventory + * @param xCorner Default Value: 8 + * @param yCorner Default Value: (rows - 4) * 18 + 103 + */ + protected void addPlayerInventory(InventoryPlayer playerInventory, int xCorner, int yCorner) { + int index = 9; + + int start = this.inventorySlots.size(); + + for(int row = 0; row < 3; row++) { + for(int col = 0; col < 9; col++) { + this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + row * 18)); + index++; + } + } + + index = 0; + for(int col = 0; col < 9; col++) { + this.addSlotToContainer(new Slot(playerInventory, index, xCorner + col * 18, yCorner + 58)); + index++; + } + + playerInventoryStart = start; + } + + @Override + protected Slot addSlotToContainer(Slot slotIn) { + if(playerInventoryStart >= 0) { + throw new SlimeknightException("BaseContainer: Player inventory has to be last slots. Add all slots before adding the player inventory."); + } + return super.addSlotToContainer(slotIn); + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) { + // we can only support inventory <-> playerInventory + if(playerInventoryStart < 0) { + // so we don't do anything if no player inventory is present because we don't know what to do + return null; + } + + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(index); + + // slot that was clicked on not empty? + if(slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + int end = this.inventorySlots.size(); + + // Is it a slot in the main inventory? (aka not player inventory) + if(index < playerInventoryStart) { + // try to put it into the player inventory (if we have a player inventory) + if(!this.mergeItemStack(itemstack1, playerInventoryStart, end, true)) { + return null; + } + } + // Slot is in the player inventory (if it exists), transfer to main inventory + else if(!this.mergeItemStack(itemstack1, 0, playerInventoryStart, false)) { + return null; + } + + if(itemstack1.stackSize == 0) { + slot.putStack(null); + } + else { + slot.onSlotChanged(); + } + } + + return itemstack; + } + + // Fix for a vanilla bug: doesn't take Slot.getMaxStackSize into account + protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { + return mergeItemStackRefill(stack, startIndex, endIndex, useEndIndex) + || mergeItemStackMove(stack, startIndex, endIndex, useEndIndex); + } + + // only refills items that are already present + protected boolean mergeItemStackRefill(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { + if(stack.stackSize <= 0) { + return false; + } + + boolean flag1 = false; + int k = startIndex; + + if(useEndIndex) { + k = endIndex - 1; + } + + Slot slot; + ItemStack itemstack1; + + if(stack.isStackable()) { + while(stack.stackSize > 0 && (!useEndIndex && k < endIndex || useEndIndex && k >= startIndex)) { + slot = (Slot) this.inventorySlots.get(k); + itemstack1 = slot.getStack(); + + if(itemstack1 != null && itemstack1.getItem() == stack.getItem() && (!stack.getHasSubtypes() + || stack.getMetadata() == itemstack1 + .getMetadata()) && ItemStack.areItemStackTagsEqual(stack, itemstack1)) { + int l = itemstack1.stackSize + stack.stackSize; + int limit = Math.min(stack.getMaxStackSize(), slot.getItemStackLimit(stack)); + + if(l <= limit) { + stack.stackSize = 0; + itemstack1.stackSize = l; + slot.onSlotChanged(); + flag1 = true; + } + else if(itemstack1.stackSize < limit) { + stack.stackSize -= limit - itemstack1.stackSize; + itemstack1.stackSize = limit; + slot.onSlotChanged(); + flag1 = true; + } + } + + if(useEndIndex) { + --k; + } + else { + ++k; + } + } + } + + return flag1; + } + + // only moves items into empty slots + protected boolean mergeItemStackMove(ItemStack stack, int startIndex, int endIndex, boolean useEndIndex) { + if(stack.stackSize <= 0) { + return false; + } + + boolean flag1 = false; + int k; + + if(useEndIndex) { + k = endIndex - 1; + } + else { + k = startIndex; + } + + while(!useEndIndex && k < endIndex || useEndIndex && k >= startIndex) { + Slot slot = (Slot) this.inventorySlots.get(k); + ItemStack itemstack1 = slot.getStack(); + + if(itemstack1 == null && slot.isItemValid(stack)) // Forge: Make sure to respect isItemValid in the slot. + { + int limit = slot.getItemStackLimit(stack); + ItemStack stack2 = stack.copy(); + if(stack2.stackSize > limit) { + stack2.stackSize = limit; + stack.stackSize -= limit; + } + else { + stack.stackSize = 0; + } + slot.putStack(stack2); + slot.onSlotChanged(); + flag1 = true; + + if(stack.stackSize == 0) { + break; + } + } + + if(useEndIndex) { + --k; + } + else { + ++k; + } + } + + + return flag1; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java b/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java new file mode 100644 index 0000000..61b998c --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/ContainerMultiModule.java @@ -0,0 +1,284 @@ +package slimeknights.mantle.inventory; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; + +import org.apache.commons.lang3.ObjectUtils; +import org.apache.commons.lang3.tuple.Pair; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class ContainerMultiModule extends BaseContainer { + + public List subContainers = Lists.newArrayList(); + + // lookup used to redirect slot specific things to the appropriate container + protected Map slotContainerMap = Maps.newHashMap(); + protected Map> subContainerSlotRanges = Maps.newHashMap(); + protected int subContainerSlotStart = -1; + protected Set shiftClickContainers = Sets.newHashSet(); + + public ContainerMultiModule(T tile) { + super(tile); + } + + + /** + * @param subcontainer The container to add + * @param preferForShiftClick If true shift clicking on slots of the main-container will try to move to this module before the player inventory + */ + public void addSubContainer(Container subcontainer, boolean preferForShiftClick) { + if(subContainers.isEmpty()) { + subContainerSlotStart = inventorySlots.size(); + } + subContainers.add(subcontainer); + + if(preferForShiftClick) { + shiftClickContainers.add(subcontainer); + } + + int begin = inventorySlots.size(); + for(Object slot : subcontainer.inventorySlots) { + SlotWrapper wrapper = new SlotWrapper((Slot) slot); + addSlotToContainer(wrapper); + slotContainerMap.put(wrapper.slotNumber, subcontainer); + } + int end = inventorySlots.size(); + subContainerSlotRanges.put(subcontainer, Pair.of(begin, end)); + } + + public TC getSubContainer(Class clazz) { + return getSubContainer(clazz, 0); + } + + public TC getSubContainer(Class clazz, int index) { + for(Container sub : subContainers) { + if(clazz.isAssignableFrom(sub.getClass())) { + index--; + } + if(index < 0) { + return (TC) sub; + } + } + + return null; + } + + public Container getSlotContainer(int slotNumber) { + if(slotContainerMap.containsKey(slotNumber)) { + return slotContainerMap.get(slotNumber); + } + + return this; + } + + @Override + public boolean canInteractWith(EntityPlayer playerIn) { + // check if subcontainers are valid + for(Container sub : subContainers) { + if(!sub.canInteractWith(playerIn)) { + return false; + } + } + + return super.canInteractWith(playerIn); + } + + + @Override + public void onContainerClosed(EntityPlayer playerIn) { + for(Container sub : subContainers) { + sub.onContainerClosed(playerIn); + } + + super.onContainerClosed(playerIn); + } + + @Override + public ItemStack slotClick(int slotId, int clickedButton, int mode, EntityPlayer playerIn) { + if(slotId == -999 && mode == 5) { + for(Container container : subContainers) { + container.slotClick(slotId, clickedButton, mode, playerIn); + } + } +/* + if(slotContainerMap.containsKey(slotId)) { + int actualId = slotId; + if(this.inventorySlots.get(slotId) instanceof SlotWrapper) { + actualId = ((SlotWrapper) this.inventorySlots.get(slotId)).parent.slotNumber; + } + return slotContainerMap.get(slotId).slotClick(actualId, clickedButton, mode, playerIn); + }*/ + + return super.slotClick(slotId, clickedButton, mode, playerIn); + } + + // More sophisticated version of the one in BaseContainer + // Takes submodules into account when shiftclicking! + @Override + public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) { + Slot slot = (Slot) this.inventorySlots.get(index); + + if(slot == null || !slot.getHasStack()) { + return null; + } + + ItemStack ret = slot.getStack().copy(); + ItemStack itemstack = slot.getStack().copy(); + + Container container = getSlotContainer(index); + boolean nothingDone = true; + + // Is the slot from a module? + if(container != this) { + // Try moving module -> tile inventory + nothingDone &= moveToTileInventory(itemstack); + + // Try moving module -> player inventory + nothingDone &= moveToPlayerInventory(itemstack); + } + // Is the slot from the tile? + else if(index < subContainerSlotStart || (index < playerInventoryStart && subContainerSlotStart < 0)) { + // Try moving tile -> preferred modules + nothingDone &= refillAnyContainer(itemstack, subContainers); + + // Try moving module -> player inventory + nothingDone &= moveToPlayerInventory(itemstack); + + // Try moving module -> all submodules + nothingDone &= moveToAnyContainer(itemstack, subContainers); + } + // Slot is from the player inventory (if present) + else if(index >= playerInventoryStart && playerInventoryStart >= 0) { + // Try moving player -> tile inventory + nothingDone &= moveToTileInventory(itemstack); + + // try moving player -> modules + nothingDone &= moveToAnyContainer(itemstack, subContainers); + } + // you violated some assumption or something. Shame on you. + else { + return null; + } + + if(nothingDone) { + return null; + } + + return notifySlotAfterTransfer(playerIn, itemstack, ret, slot); + } + + protected ItemStack notifySlotAfterTransfer(EntityPlayer player, ItemStack stack, ItemStack original, Slot slot) { + // notify slot + slot.onSlotChange(stack, original); + + if(stack.stackSize == original.stackSize) { + return null; + } + + // update slot we pulled from + slot.putStack(stack); + slot.onPickupFromSlot(player, stack); + + if(slot.getHasStack() && slot.getStack().stackSize == 0) { + slot.putStack(null); + } + + return original; + } + + protected boolean moveToTileInventory(ItemStack itemstack) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + int end = subContainerSlotStart; + if(end < 0) { + end = playerInventoryStart; + } + return !this.mergeItemStack(itemstack, 0, end, false); + } + + protected boolean moveToPlayerInventory(ItemStack itemstack) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + return playerInventoryStart > 0 && !this + .mergeItemStack(itemstack, playerInventoryStart, this.inventorySlots.size(), true); + } + + protected boolean moveToAnyContainer(ItemStack itemstack, Collection containers) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + for(Container submodule : containers) { + if(moveToContainer(itemstack, submodule)) { + return true; + } + } + + return false; + } + + protected boolean moveToContainer(ItemStack itemstack, Container container) { + Pair range = subContainerSlotRanges.get(container); + if(!this.mergeItemStack(itemstack, range.getLeft(), range.getRight(), false)) { + return true; + } + return false; + } + + + protected boolean refillAnyContainer(ItemStack itemstack, Collection containers) { + if(itemstack == null || itemstack.stackSize == 0) { + return false; + } + + for(Container submodule : containers) { + if(refillContainer(itemstack, submodule)) { + return true; + } + } + + return false; + } + + protected boolean refillContainer(ItemStack itemstack, Container container) { + Pair range = subContainerSlotRanges.get(container); + if(!this.mergeItemStackRefill(itemstack, range.getLeft(), range.getRight(), false)) { + return true; + } + return false; + } + + /** Searches for a sidechest to display in the UI */ + public TE detectTE(Class clazz) { + return ObjectUtils.firstNonNull(detectChest(this.pos.north(), clazz), + detectChest(this.pos.east(), clazz), + detectChest(this.pos.south(), clazz), + detectChest(this.pos.west(), clazz)); + } + + private TE detectChest(BlockPos pos, Class clazz) { + TileEntity te = this.world.getTileEntity(pos); + + if(te != null && clazz.isAssignableFrom(te.getClass())) { + return (TE) te; + } + return null; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java b/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java new file mode 100644 index 0000000..abaee40 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/ContainerSimpleChest.java @@ -0,0 +1,36 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; + +import slimeknights.mantle.tileentity.TileInventory; + +public class ContainerSimpleChest extends BaseContainer { + + public ContainerSimpleChest(TileInventory tile, int rows, int columns, InventoryPlayer playerInventory) { + super(tile); + + int index = 0; + + // chest inventory + for(int i = 0; i < rows; ++i) { + for(int j = 0; j < columns; ++j) { + // safety + if(index > tile.getSizeInventory()) { + break; + } + + this.addSlotToContainer(createSlot(tile, index, 8 + j * 18, 18 + i * 18)); + index++; + } + } + + // player inventory + addPlayerInventory(playerInventory, 17, 86); + } + + protected Slot createSlot(IInventory inventory, int index, int x, int y) { + return new Slot(inventory, index, x, y); + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/IContainerCraftingCustom.java b/src/main/java/slimeknights/mantle/inventory/IContainerCraftingCustom.java new file mode 100644 index 0000000..fa97dac --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/IContainerCraftingCustom.java @@ -0,0 +1,10 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +public interface IContainerCraftingCustom { + + void onCrafting(EntityPlayer player, ItemStack output, IInventory craftMatrix); +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java b/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java new file mode 100644 index 0000000..162162b --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotCraftingCustom.java @@ -0,0 +1,34 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.inventory.SlotCrafting; +import net.minecraft.item.ItemStack; + +public class SlotCraftingCustom extends SlotCrafting { + + private final InventoryCrafting craftMatrix; + private final IContainerCraftingCustom callback; + + /** + * @param callback Container that gets the crafting call on crafting + * @param player Player that does the crafting + * @param craftingInventory Inventory where the ingredients are taken from + * @param craftResult Inventory where the result is put + */ + public SlotCraftingCustom(IContainerCraftingCustom callback, EntityPlayer player, InventoryCrafting craftingInventory, IInventory craftResult, int slotIndex, int xPosition, int yPosition) { + super(player, craftingInventory, craftResult, slotIndex, xPosition, yPosition); + + this.craftMatrix = craftingInventory; + this.callback = callback; + } + + @Override + public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) { + net.minecraftforge.fml.common.FMLCommonHandler.instance().firePlayerCraftingEvent(playerIn, stack, craftMatrix); + this.onCrafting(stack); + + callback.onCrafting(playerIn, stack, craftMatrix); + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotOut.java b/src/main/java/slimeknights/mantle/inventory/SlotOut.java new file mode 100644 index 0000000..03764b9 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotOut.java @@ -0,0 +1,18 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + +/** Slot that can only be taken out of */ +public class SlotOut extends Slot { + + public SlotOut(IInventory inventoryIn, int index, int xPosition, int yPosition) { + super(inventoryIn, index, xPosition, yPosition); + } + + @Override + public boolean isItemValid(ItemStack stack) { + return false; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java b/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java new file mode 100644 index 0000000..29cf460 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotRestrictedItem.java @@ -0,0 +1,21 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +public class SlotRestrictedItem extends Slot { + + private final Item allowedItem; + + public SlotRestrictedItem(Item item, IInventory inventoryIn, int index, int xPosition, int yPosition) { + super(inventoryIn, index, xPosition, yPosition); + allowedItem = item; + } + + @Override + public boolean isItemValid(ItemStack stack) { + return stack != null && stack.getItem() == allowedItem; + } +} diff --git a/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java b/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java new file mode 100644 index 0000000..8d7fbf0 --- /dev/null +++ b/src/main/java/slimeknights/mantle/inventory/SlotWrapper.java @@ -0,0 +1,46 @@ +package slimeknights.mantle.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +/** + * Used to wrap the slots inside Modules/Subcontainers + */ +public class SlotWrapper extends Slot { + + public final Slot parent; + + public SlotWrapper(Slot slot) { + super(slot.inventory, slot.getSlotIndex(), slot.xDisplayPosition, slot.yDisplayPosition); + this.parent = slot; + } + + @Override + public void onSlotChange(ItemStack p_75220_1_, ItemStack p_75220_2_) { + parent.onSlotChange(p_75220_1_, p_75220_2_); + } + + @Override + public void onSlotChanged() { + parent.onSlotChanged(); + } + + @Override + public boolean isItemValid(ItemStack stack) { + return parent.isItemValid(stack); + } + + @Override + public boolean canTakeStack(EntityPlayer playerIn) { + return parent.canTakeStack(playerIn); + } + + @SideOnly(Side.CLIENT) + @Override + public boolean canBeHovered() { + return parent.canBeHovered(); + } +} diff --git a/src/main/java/slimeknights/mantle/item/ItemBlockMeta.java b/src/main/java/slimeknights/mantle/item/ItemBlockMeta.java new file mode 100644 index 0000000..6e22a82 --- /dev/null +++ b/src/main/java/slimeknights/mantle/item/ItemBlockMeta.java @@ -0,0 +1,72 @@ +package slimeknights.mantle.item; + +import net.minecraft.block.Block; +import net.minecraft.block.properties.IProperty; +import net.minecraft.block.state.IBlockState; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemColored; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.registry.GameData; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.Collection; +import java.util.List; +import java.util.Locale; + +import slimeknights.mantle.util.LocUtils; + +public class ItemBlockMeta extends ItemColored { + + protected IProperty mappingProperty; + + public ItemBlockMeta(Block block) { + super(block, true); + } + + @Override + public String getUnlocalizedName(ItemStack stack) { + if(mappingProperty == null) return super.getUnlocalizedName(stack); + + IBlockState state = block.getStateFromMeta(stack.getMetadata()); + String name = state.getValue(mappingProperty).toString().toLowerCase(Locale.US); + return super.getUnlocalizedName(stack) + "." + name; + } + + public static void setMappingProperty(Block block, IProperty property) { + ((ItemBlockMeta)Item.getItemFromBlock(block)).mappingProperty = property; + } + + @Override + public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) { + if(StatCollector.canTranslate(this.getUnlocalizedName(stack) + ".tooltip")) { + tooltip.add(EnumChatFormatting.GRAY.toString() + + LocUtils.translateRecursive(this.getUnlocalizedName(stack) + ".tooltip")); + } + else if(StatCollector.canTranslate(super.getUnlocalizedName(stack) + ".tooltip")) { + tooltip.add(EnumChatFormatting.GRAY.toString() + LocUtils.translateRecursive(super.getUnlocalizedName(stack) + ".tooltip")); + } + super.addInformation(stack, playerIn, tooltip, advanced); + } + + @SideOnly(Side.CLIENT) + public void registerItemModels() { + final Item item = this; + final ResourceLocation loc = (ResourceLocation) GameData.getBlockRegistry().getNameForObject(block); + + + for(Comparable o : (Collection)mappingProperty.getAllowedValues()) { + int meta = block.getMetaFromState(block.getDefaultState().withProperty(mappingProperty, o)); + String name = mappingProperty.getName(o); + + ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(loc, mappingProperty.getName() + "=" + name)); + } + } +} diff --git a/src/main/java/slimeknights/mantle/item/ItemEdible.java b/src/main/java/slimeknights/mantle/item/ItemEdible.java new file mode 100644 index 0000000..877ebd6 --- /dev/null +++ b/src/main/java/slimeknights/mantle/item/ItemEdible.java @@ -0,0 +1,110 @@ +package slimeknights.mantle.item; + +import gnu.trove.map.hash.TIntFloatHashMap; +import gnu.trove.map.hash.TIntIntHashMap; +import gnu.trove.map.hash.TIntObjectHashMap; + +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemFood; +import net.minecraft.item.ItemStack; +import net.minecraft.potion.PotionEffect; +import net.minecraft.world.World; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.List; + +public class ItemEdible extends ItemFood { + + // we use this so we don't have to copy all the logic + private ItemMetaDynamic dynamic; + + protected TIntIntHashMap foodLevels; + protected TIntFloatHashMap saturations; + protected TIntObjectHashMap potionEffects; + + public ItemEdible() { + super(0, 0, false); + this.setHasSubtypes(true); + + dynamic = new ItemMetaDynamic(); + foodLevels = new TIntIntHashMap(); + saturations = new TIntFloatHashMap(); + potionEffects = new TIntObjectHashMap(); + } + + /** + * Add a new food type! + * @param meta Metadata to use, has to be free + * @param food How much food it restores on eating + * @param saturation Saturation multiplier on the food + * @param name Unlocalized postfix + * @param effects PotionEffects that will be applied on eating. The PotionEffect passed will be directly applied + * @return Itemstack containing the registered item + */ + public ItemStack addFood(int meta, int food, float saturation, String name, PotionEffect... effects) { + dynamic.addMeta(meta, name); + foodLevels.put(meta, food); + saturations.put(meta, saturation); + potionEffects.put(meta, effects); + + return new ItemStack(this, 1, meta); + } + + @Override + public float getSaturationModifier(ItemStack stack) { + return saturations.get(stack.getMetadata()); // should call getMetadata below + // default value if meta not present is 0 + } + + @Override + public int getHealAmount(ItemStack stack) { + return foodLevels.get(stack.getMetadata()); // should call getMetadata below + // default value if meta not present is 0 + } + + @Override + protected void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) { + if (!worldIn.isRemote) + { + for(PotionEffect potion : potionEffects.get(stack.getMetadata())) { + player.addPotionEffect(new PotionEffect(potion.getPotionID(), potion.getDuration(), potion.getAmplifier(), potion.getIsAmbient(), potion.getIsShowParticles())); + } + } + } + + /* ItemMetaDynamic Functionality */ + @Override + public Item setUnlocalizedName(String unlocalizedName) { + dynamic.setUnlocalizedName(unlocalizedName); + return super.setUnlocalizedName(unlocalizedName); + } + + @Override + public String getUnlocalizedName(ItemStack stack) { + return dynamic.getUnlocalizedName(stack); + } + + @Override + public int getMetadata(ItemStack stack) { + return dynamic.getMetadata(stack); + } + + @Override + public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) { + dynamic.addInformation(stack, playerIn, tooltip, advanced); + } + + @SideOnly(Side.CLIENT) + @Override + public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) { + dynamic.getSubItems(itemIn, tab, subItems); + } + + @SideOnly(Side.CLIENT) + public void registerItemModels(final String prefix) { + dynamic.registerItemModels(prefix, this); + } +} diff --git a/src/main/java/slimeknights/mantle/item/ItemMetaDynamic.java b/src/main/java/slimeknights/mantle/item/ItemMetaDynamic.java new file mode 100644 index 0000000..fae5f15 --- /dev/null +++ b/src/main/java/slimeknights/mantle/item/ItemMetaDynamic.java @@ -0,0 +1,132 @@ +package slimeknights.mantle.item; + +import gnu.trove.map.hash.TIntObjectHashMap; +import gnu.trove.procedure.TIntObjectProcedure; + +import net.minecraft.client.resources.model.ModelBakery; +import net.minecraft.client.resources.model.ModelResourceLocation; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.StatCollector; +import net.minecraftforge.client.model.ModelLoader; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.relauncher.Side; +import net.minecraftforge.fml.relauncher.SideOnly; + +import java.util.Arrays; +import java.util.List; +import java.util.Locale; + +import slimeknights.mantle.util.LocUtils; + +/** + * Item representing a dynamic amount of different items represented by meta. + * Only returns valid metadatas. The validity is determined by a bitmask. + * Current maximum is 64 metas - that should suffice for most applications. + */ +public class ItemMetaDynamic extends Item { + + private static int MAX = (2 << 16) - 1; + + protected boolean[] availabilityMask; // boolean[] actually is much more performant for our case than BitSet + protected TIntObjectHashMap names; + + public ItemMetaDynamic() { + availabilityMask = new boolean[1]; + names = new TIntObjectHashMap(); + + this.setHasSubtypes(true); + } + + /** + * Add a valid metadata. + * @param meta The metadata value + * @param name The name used for registering the itemmodel as well as the unlocalized name of the meta. The unlocalized name will be lowercased and stripped of whitespaces. + * @return An itemstack representing the Item-Meta combination. + */ + public ItemStack addMeta(int meta, String name) { + if(meta > MAX) { + throw new IllegalArgumentException(String.format("Metadata for %s too high, highest supported value is %d. Meta was %d", name, MAX, meta)); + } + else if(isValid(meta)) { + throw new IllegalArgumentException(String.format("Metadata for %s is already taken. Meta %d is %s", name, meta, names.get(meta))); + } + + while(meta >= availabilityMask.length) { + availabilityMask = Arrays.copyOf(availabilityMask, availabilityMask.length*2); + } + setValid(meta); + names.put(meta, name); + return new ItemStack(this, 1, meta); + } + + @Override + public String getUnlocalizedName(ItemStack stack) { + int meta = stack.getMetadata(); // should call getMetadata below + if(isValid(meta)) + return super.getUnlocalizedName(stack) + "." + LocUtils.makeLocString(names.get(meta)); + else + return super.getUnlocalizedName(stack); + } + + @Override + public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) { + for(int i = 0; i <= availabilityMask.length; i++) { + if(isValid(i)) { + subItems.add(new ItemStack(itemIn, 1, i)); + } + } + } + + @Override + public int getMetadata(int damage) { + int meta = super.getMetadata(damage); + return isValid(meta) ? meta : 0; + } + + protected void setValid(int meta) { + availabilityMask[meta] = true; + } + + protected boolean isValid(int meta) { + if(meta > MAX || meta >= availabilityMask.length) { + return false; + } + return availabilityMask[meta]; + } + + @SideOnly(Side.CLIENT) + public void registerItemModels(final String prefix) { + registerItemModels(prefix, this); + } + + @SideOnly(Side.CLIENT) + protected void registerItemModels(final String prefix, final Item item) { + final String resourceId = Loader.instance().activeModContainer().getModId().toLowerCase(); + names.forEachEntry(new TIntObjectProcedure() { + @Override + public boolean execute(int meta, String name) { + name = String.format("%s:%s%s", resourceId, prefix, name); + ModelBakery.addVariantName(item, name); + // tell the game which model to use for this item-meta combination + ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(name, "inventory")); + return true; + } + }); + } + + @Override + public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) { + if(StatCollector.canTranslate(this.getUnlocalizedName(stack) + ".tooltip")) { + tooltip.add(EnumChatFormatting.GRAY.toString() + + LocUtils.translateRecursive(this.getUnlocalizedName(stack) + ".tooltip")); + } + else if(StatCollector.canTranslate(super.getUnlocalizedName(stack) + ".tooltip")) { + tooltip.add(EnumChatFormatting.GRAY.toString() + LocUtils.translateRecursive(super.getUnlocalizedName(stack) + ".tooltip")); + } + super.addInformation(stack, playerIn, tooltip, advanced); + } +} diff --git a/src/main/java/slimeknights/mantle/multiblock/IMasterLogic.java b/src/main/java/slimeknights/mantle/multiblock/IMasterLogic.java new file mode 100644 index 0000000..1f66dfa --- /dev/null +++ b/src/main/java/slimeknights/mantle/multiblock/IMasterLogic.java @@ -0,0 +1,12 @@ +package slimeknights.mantle.multiblock; + +import net.minecraft.util.BlockPos; + +public interface IMasterLogic +{ + /** Called when servants change their state + * + * @param pos servant position + */ + public void notifyChange(IServantLogic servant, BlockPos pos); +} diff --git a/src/main/java/slimeknights/mantle/multiblock/IMasterNode.java b/src/main/java/slimeknights/mantle/multiblock/IMasterNode.java new file mode 100644 index 0000000..312c25d --- /dev/null +++ b/src/main/java/slimeknights/mantle/multiblock/IMasterNode.java @@ -0,0 +1,8 @@ +package slimeknights.mantle.multiblock; + +public interface IMasterNode extends IMasterLogic, IServantLogic +{ + public boolean isCurrentlyMaster(); + + public boolean isEquivalentMaster(IMasterLogic master); +} diff --git a/src/main/java/slimeknights/mantle/multiblock/IServantLogic.java b/src/main/java/slimeknights/mantle/multiblock/IServantLogic.java new file mode 100644 index 0000000..3319277 --- /dev/null +++ b/src/main/java/slimeknights/mantle/multiblock/IServantLogic.java @@ -0,0 +1,41 @@ +package slimeknights.mantle.multiblock; + +import net.minecraft.util.BlockPos; +import net.minecraft.world.World; + +public interface IServantLogic +{ + public BlockPos getMasterPosition(); + + /** The block should already have a valid master */ + public void notifyMasterOfChange(); + + /** Checks if this block can be tied to this master + * + * @param master + * @param world the world of master + * @param pos position of master + * @return whether the servant can be tied to this master + */ + + public boolean setPotentialMaster(IMasterLogic master, World world, BlockPos pos); + + /** Used to set and verify that this is the block's master + * + * @param master + * @param world + * @param pos position of master + * @return Is this block tied to this master? + */ + + public boolean verifyMaster(IMasterLogic master, World world, BlockPos pos); + + /** Exactly what it says on the tin + * + * @param master + * @param world + * @param pos position of master + */ + + public void invalidateMaster(IMasterLogic master, World world, BlockPos pos); +} diff --git a/src/main/java/slimeknights/mantle/multiblock/MultiServantLogic.java b/src/main/java/slimeknights/mantle/multiblock/MultiServantLogic.java new file mode 100644 index 0000000..c29b3c2 --- /dev/null +++ b/src/main/java/slimeknights/mantle/multiblock/MultiServantLogic.java @@ -0,0 +1,197 @@ +package slimeknights.mantle.multiblock; + +import net.minecraft.block.Block; +import net.minecraft.block.state.IBlockState; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.Packet; +import net.minecraft.network.play.server.S35PacketUpdateTileEntity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.BlockPos; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; +import net.minecraftforge.fml.common.registry.GameData; + +public class MultiServantLogic extends TileEntity implements IServantLogic +{ + boolean hasMaster; + + BlockPos master; + + Block masterBlock; + + IBlockState state; + + public boolean canUpdate() + { + return false; + } + + public boolean getHasMaster() + { + return this.hasMaster; + } + + public boolean hasValidMaster() + { + if (!this.hasMaster) + { + return false; + } + + if (this.worldObj.getBlockState(this.master).getBlock() == this.masterBlock && this.worldObj.getBlockState(this.master) == this.state) + { + return true; + } + else + { + this.hasMaster = false; + this.master = null; + return false; + } + } + + @Override + public BlockPos getMasterPosition() + { + return this.master; + } + + public void overrideMaster(BlockPos pos) + { + this.hasMaster = true; + this.master = pos; + this.state = this.worldObj.getBlockState(this.master); + this.masterBlock = this.state.getBlock(); + } + + public void removeMaster() + { + this.hasMaster = false; + this.master = null; + this.masterBlock = null; + this.state = null; + } + + @Override + public boolean setPotentialMaster(IMasterLogic master, World w, BlockPos pos) + { + return !this.hasMaster; + } + + @Deprecated + public boolean verifyMaster(IMasterLogic logic, BlockPos pos) + { + return this.master.equals(pos) && this.worldObj.getBlockState(pos) == this.state && this.worldObj.getBlockState(pos).getBlock() == this.masterBlock; + } + + @Override + public boolean verifyMaster(IMasterLogic logic, World world, BlockPos pos) + { + if (this.hasMaster) + { + return this.hasValidMaster(); + } + else + { + this.overrideMaster(pos); + return true; + } + } + + @Override + public void invalidateMaster(IMasterLogic master, World w, BlockPos pos) + { + this.hasMaster = false; + master = null; + } + + @Override + public void notifyMasterOfChange() + { + if (this.hasValidMaster()) + { + IMasterLogic logic = (IMasterLogic) this.worldObj.getTileEntity(this.master); + logic.notifyChange(this, this.pos); + } + } + + public void readCustomNBT(NBTTagCompound tags) + { + this.hasMaster = tags.getBoolean("hasMaster"); + if (this.hasMaster) + { + int xCenter = tags.getInteger("xCenter"); + int yCenter = tags.getInteger("yCenter"); + int zCenter = tags.getInteger("zCenter"); + this.master = new BlockPos(xCenter, yCenter, zCenter); + this.masterBlock = GameData.getBlockRegistry().getObject(new ResourceLocation(tags.getString("MasterBlockName"))); + this.state = Block.getStateById(tags.getInteger("masterState")); + } + } + + public void writeCustomNBT(NBTTagCompound tags) + { + tags.setBoolean("hasMaster", this.hasMaster); + if (this.hasMaster) + { + tags.setInteger("xCenter", this.master.getX()); + tags.setInteger("yCenter", this.master.getY()); + tags.setInteger("zCenter", this.master.getZ()); + tags.setString("MasterBlockName", GameData.getBlockRegistry().getNameForObject(this.masterBlock).toString()); + tags.setInteger("masterState", Block.getStateId(this.state)); + } + } + + @Override + public void readFromNBT(NBTTagCompound tags) + { + super.readFromNBT(tags); + this.readCustomNBT(tags); + } + + @Override + public void writeToNBT(NBTTagCompound tags) + { + super.writeToNBT(tags); + this.writeCustomNBT(tags); + } + + /* Packets */ + @Override + public Packet getDescriptionPacket() + { + NBTTagCompound tag = new NBTTagCompound(); + this.writeCustomNBT(tag); + return new S35PacketUpdateTileEntity(this.pos, 1, tag); + } + + @Override + public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) + { + this.readCustomNBT(packet.getNbtCompound()); + this.worldObj.notifyLightSet(this.pos); + this.worldObj.markBlockForUpdate(this.pos); + } + + @Override + public World getWorld() + { + return this.worldObj; + } + + @Deprecated + public boolean setMaster(BlockPos pos) + { + if (!this.hasMaster || this.worldObj.getBlockState(this.master) != this.state || (this.worldObj.getBlockState(this.master).getBlock() != this.masterBlock)) + { + this.overrideMaster(pos); + return true; + } + else + { + return false; + } + } + +} diff --git a/src/main/java/slimeknights/mantle/network/AbstractPacket.java b/src/main/java/slimeknights/mantle/network/AbstractPacket.java new file mode 100644 index 0000000..2ef620b --- /dev/null +++ b/src/main/java/slimeknights/mantle/network/AbstractPacket.java @@ -0,0 +1,31 @@ +package slimeknights.mantle.network; + +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.util.BlockPos; +import net.minecraftforge.fml.common.network.simpleimpl.IMessage; +import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; +import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraftforge.fml.relauncher.Side; + +import io.netty.buffer.ByteBuf; + +public abstract class AbstractPacket implements IMessage { + + public abstract IMessage handleClient(NetHandlerPlayClient netHandler); + + public abstract IMessage handleServer(NetHandlerPlayServer netHandler); + + protected void writePos(BlockPos pos, ByteBuf buf) { + buf.writeInt(pos.getX()); + buf.writeInt(pos.getY()); + buf.writeInt(pos.getZ()); + } + + protected BlockPos readPos(ByteBuf buf) { + int x = buf.readInt(); + int y = buf.readInt(); + int z = buf.readInt(); + return new BlockPos(x, y, z); + } +} diff --git a/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java b/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java new file mode 100644 index 0000000..8e9a563 --- /dev/null +++ b/src/main/java/slimeknights/mantle/network/AbstractPacketThreadsafe.java @@ -0,0 +1,42 @@ +package slimeknights.mantle.network; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.network.NetHandlerPlayClient; +import net.minecraft.network.NetHandlerPlayServer; +import net.minecraft.server.MinecraftServer; +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.network.simpleimpl.IMessage; + +/** + * Threadsafe integration of the abstract packet. + * Basically if you're doing something that has any influence on the world you should use this. + * (That's ~everything) + */ +public abstract class AbstractPacketThreadsafe extends AbstractPacket { + + @Override + public final IMessage handleClient(final NetHandlerPlayClient netHandler) { + Minecraft.getMinecraft().addScheduledTask(new Runnable() { + @Override + public void run() { + handleClientSafe(netHandler); + } + }); + return null; + } + + @Override + public final IMessage handleServer(final NetHandlerPlayServer netHandler) { + MinecraftServer.getServer().addScheduledTask(new Runnable() { + @Override + public void run() { + handleServerSafe(netHandler); + } + }); + return null; + } + + public abstract void handleClientSafe(NetHandlerPlayClient netHandler); + + public abstract void handleServerSafe(NetHandlerPlayServer netHandler); +} diff --git a/src/main/java/slimeknights/mantle/network/NetworkWrapper.java b/src/main/java/slimeknights/mantle/network/NetworkWrapper.java new file mode 100644 index 0000000..cfa3ea3 --- /dev/null +++ b/src/main/java/slimeknights/mantle/network/NetworkWrapper.java @@ -0,0 +1,62 @@ +package slimeknights.mantle.network; + +import net.minecraftforge.fml.common.network.NetworkRegistry; +import net.minecraftforge.fml.common.network.simpleimpl.IMessage; +import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; +import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; +import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; +import net.minecraftforge.fml.relauncher.Side; + +/** + * A small network implementation/wrapper using AbstractPackets instead of IMessages. + * Instantiate in your mod class and register your packets accordingly. + */ +public class NetworkWrapper { + + public final SimpleNetworkWrapper network; + protected final AbstactPacketHandler handler; + private int id = 0; + + public NetworkWrapper(String channelName) { + network = NetworkRegistry.INSTANCE.newSimpleChannel(channelName); + handler = new AbstactPacketHandler(); + } + + /** + * Packet will be received on both cliend and server side. + */ + public void registerPacket(Class packetClazz) { + registerPacketClient(packetClazz); + registerPacketServer(packetClazz); + } + + /** + * Packet will only be received on the client side + */ + public void registerPacketClient(Class packetClazz) { + registerPacketImpl(packetClazz, Side.CLIENT); + } + + /** + * Packet will only be received on the server side + */ + public void registerPacketServer(Class packetClazz) { + registerPacketImpl(packetClazz, Side.SERVER); + } + + private void registerPacketImpl(Class packetClazz, Side side) { + network.registerMessage(handler, packetClazz, id++, side); + } + + public static class AbstactPacketHandler implements IMessageHandler { + @Override + public IMessage onMessage(AbstractPacket packet, MessageContext ctx) { + if(ctx.side == Side.SERVER) { + return packet.handleServer(ctx.getServerHandler()); + } + else { + return packet.handleClient(ctx.getClientHandler()); + } + } + } +} diff --git a/src/main/java/slimeknights/mantle/property/PropertyString.java b/src/main/java/slimeknights/mantle/property/PropertyString.java new file mode 100644 index 0000000..4fc3f20 --- /dev/null +++ b/src/main/java/slimeknights/mantle/property/PropertyString.java @@ -0,0 +1,32 @@ +package slimeknights.mantle.property; + +import net.minecraftforge.common.property.IUnlistedProperty; + +public class PropertyString implements IUnlistedProperty { + + private final String name; + + public PropertyString(String name) { + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public boolean isValid(String value) { + return !value.isEmpty(); + } + + @Override + public Class getType() { + return String.class; + } + + @Override + public String valueToString(String value) { + return value; + } +} diff --git a/src/main/java/slimeknights/mantle/property/PropertyUnlistedDirection.java b/src/main/java/slimeknights/mantle/property/PropertyUnlistedDirection.java new file mode 100644 index 0000000..8f4bd5a --- /dev/null +++ b/src/main/java/slimeknights/mantle/property/PropertyUnlistedDirection.java @@ -0,0 +1,38 @@ +package slimeknights.mantle.property; + +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import com.google.common.collect.Lists; + +import net.minecraft.block.properties.PropertyDirection; +import net.minecraft.util.EnumFacing; +import net.minecraftforge.common.property.IUnlistedProperty; + +import java.util.Collection; + +public class PropertyUnlistedDirection extends PropertyDirection implements IUnlistedProperty { + + public PropertyUnlistedDirection(String name, Collection values) { + super(name, values); + } + + public PropertyUnlistedDirection(String name, Predicate filter) { + this(name, Collections2.filter(Lists.newArrayList(EnumFacing.values()), filter)); + } + + @Override + public boolean isValid(EnumFacing value) { + return true; + } + + @Override + public Class getType() { + return this.getValueClass(); + } + + @Override + public String valueToString(EnumFacing value) { + return getName(value); + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/config/ForgeCFG.java b/src/main/java/slimeknights/mantle/pulsar/config/ForgeCFG.java new file mode 100644 index 0000000..3efecf6 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/config/ForgeCFG.java @@ -0,0 +1,71 @@ +package slimeknights.mantle.pulsar.config; + +import java.io.File; +import java.util.Locale; + +import slimeknights.mantle.pulsar.pulse.PulseMeta; + +import net.minecraftforge.common.config.ConfigCategory; +import net.minecraftforge.common.config.Configuration; +import net.minecraftforge.common.config.Property; +import net.minecraftforge.fml.common.Loader; + +/** + * Mantle specific pulsar addon class to support using the forge CFG format for configurations + * @author progwml6 + */ +public class ForgeCFG implements IConfiguration +{ + + private Configuration config; + + private final String confPath; + + private final String description; + + /** + * Creates a new Configuration object. + * + * Do NOT make this the same as the overall mod configuration; it will clobber it! + * + * @param confName The config file name (without path or .cfg suffix) + * @param description The description for the group that the config entries will be placed in. + */ + public ForgeCFG(String confName, String description) + { + this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".cfg"; + this.description = description.toLowerCase(Locale.US); + } + + @Override + public void load() + { + config = new Configuration(new File(this.confPath), "1"); + config.load(); + } + + @Override + public boolean isModuleEnabled(PulseMeta meta) + { + Property prop = config.get(this.description, meta.getId(), meta.isEnabled(), meta.getDescription()); + prop.setRequiresMcRestart(true); + return prop.getBoolean(meta.isEnabled()); + } + + @Override + public void flush() + { + if (config.hasChanged()) + { + config.save(); + } + } + + public Configuration getConfig() { + return config; + } + + public ConfigCategory getCategory() { + return config.getCategory(this.description); + } +} diff --git a/src/mantle/pulsar/config/IConfiguration.java b/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java similarity index 74% rename from src/mantle/pulsar/config/IConfiguration.java rename to src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java index 01c67eb..9f40530 100644 --- a/src/mantle/pulsar/config/IConfiguration.java +++ b/src/main/java/slimeknights/mantle/pulsar/config/IConfiguration.java @@ -1,12 +1,15 @@ -package mantle.pulsar.config; +package slimeknights.mantle.pulsar.config; -import mantle.pulsar.pulse.PulseMeta; +import slimeknights.mantle.pulsar.pulse.PulseMeta; + +import javax.annotation.ParametersAreNonnullByDefault; /** * Interface for config handlers. * * @author Arkan */ +@ParametersAreNonnullByDefault public interface IConfiguration { /** diff --git a/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java b/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java new file mode 100644 index 0000000..3524b00 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/control/PulseManager.java @@ -0,0 +1,253 @@ +package slimeknights.mantle.pulsar.control; + +import com.google.common.eventbus.EventBus; +import com.google.common.eventbus.Subscribe; + +import net.minecraftforge.fml.common.FMLCommonHandler; +import net.minecraftforge.fml.common.FMLModContainer; +import net.minecraftforge.fml.common.Loader; +import net.minecraftforge.fml.common.ModContainer; +import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +import javax.annotation.ParametersAreNonnullByDefault; + +import slimeknights.mantle.pulsar.config.IConfiguration; +import slimeknights.mantle.pulsar.flightpath.Flightpath; +import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; +import slimeknights.mantle.pulsar.flightpath.lib.AnnotationLocator; +import slimeknights.mantle.pulsar.internal.BusExceptionHandler; +import slimeknights.mantle.pulsar.internal.Configuration; +import slimeknights.mantle.pulsar.internal.CrashHandler; +import slimeknights.mantle.pulsar.pulse.Pulse; +import slimeknights.mantle.pulsar.pulse.PulseMeta; + +/** + * Manager class for a given mods Pulses. + * + * This MUST be constructed by a mod BEFORE preinit as it registers on to the mod event bus - a static block would serve + * for this. No more Pulses can be registered after preinit has been caught, so assume preinit is too late to register + * new Pulses. + * + * Each Pulsar-enabled mod should create one and only one of these to manage its Pulses. + * + * @author Arkan + */ +@SuppressWarnings("unused") +@ParametersAreNonnullByDefault +public class PulseManager { + + private Logger log; + private final boolean useConfig; + + private final LinkedHashMap pulses = new LinkedHashMap(); + // Use the Google @Subscribe to avoid confusion/breaking changes. + private final Flightpath flightpath = new Flightpath(new AnnotationLocator(Subscribe.class)); + + private boolean blockNewRegistrations = false; + private boolean configLoaded = false; + private IConfiguration conf; + private String id; + + /** + * Configuration-using constructor. + * + * This form creates a PulseManager that supports configuration of Pulses by file. + * + * @param configName The config file name. + */ + public PulseManager(String configName) { + init(); + useConfig = true; + conf = new Configuration(configName, log); + } + + /** + * Custom configuration-using constructor. + * + * Don't like JSON? Heathen. Lets you handle configuration, to whatever media you like - File, database, death star. + * Whatever really. See {@link slimeknights.mantle.pulsar.config.IConfiguration}. + * + * @param config Configuration handler. + */ + public PulseManager(IConfiguration config) { + init(); + useConfig = true; + conf = config; + } + + /** + * Shared initialiser code between all the constructors. + */ + private void init() { + String modId = Loader.instance().activeModContainer().getModId(); + this.id = modId; + log = LogManager.getLogger("Pulsar-" + modId); + flightpath.setExceptionHandler(new BusExceptionHandler(modId)); + FMLCommonHandler.instance().registerCrashCallable(new CrashHandler(modId, this)); + // Attach us to the mods FML bus + attachToContainerEventBus(this); + } + + /** + * Overrides Pulsars default behaviour when a pulse emits an exception. See Flightpath's documentation. + * + * @param handler The Flightpath-compatible exception handler to use. + */ + public void setPulseExceptionHandler(IExceptionHandler handler) { + flightpath.setExceptionHandler(handler); + } + + /** + * Register a new Pulse with the manager. + * + * This CANNOT be done after preinit has been invoked. + * + * @param pulse The Pulse to register. + */ + public void registerPulse(Object pulse) { + if (blockNewRegistrations) throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: " + + pulse); + if (!configLoaded) { + conf.load(); + configLoaded = true; + } + + String id, description, deps; + boolean forced, enabled, defaultEnabled, missingDeps = false; + + try { + Pulse p = pulse.getClass().getAnnotation(Pulse.class); + id = p.id(); + description = p.description(); + deps = p.modsRequired(); + forced = p.forced(); + enabled = p.defaultEnable(); + defaultEnabled = p.defaultEnable(); + } catch (NullPointerException ex) { + throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse); + } + + // Work around Java not allowing default-null fields. + if (description.equals("")) description = null; + + if (!deps.equals("")) { + String[] parsedDeps = deps.split(";"); + for (String s : parsedDeps) { + if (!Loader.isModLoaded(s)) { + log.info("Skipping Pulse " + id + "; missing dependency: " + s); + missingDeps = true; + enabled = false; + break; + } + } + } + + PulseMeta meta = new PulseMeta(id, description, forced, enabled, defaultEnabled); + meta.setMissingDeps(missingDeps); + meta.setEnabled(getEnabledFromConfig(meta)); + + if (meta.isEnabled()) { + pulses.put(pulse, meta); + flightpath.register(pulse); + } + } + + /** + * Helper to attach a given object to the mod container event bus. + * + * @param obj Object to register. + */ + private void attachToContainerEventBus(Object obj) { + ModContainer cnt = Loader.instance().activeModContainer(); + log.debug("Attaching [" + obj + "] to event bus for container [" + cnt + "]"); + try { + FMLModContainer mc = (FMLModContainer)cnt; + Field ebf = mc.getClass().getDeclaredField("eventBus"); + + boolean access = ebf.isAccessible(); + ebf.setAccessible(true); + EventBus eb = (EventBus)ebf.get(mc); + ebf.setAccessible(access); + + eb.register(obj); + } catch (NoSuchFieldException nsfe) { + throw new RuntimeException("Pulsar >> Incompatible FML mod container (missing eventBus field) - wrong Forge version?"); + } catch (IllegalAccessException iae) { + throw new RuntimeException("Pulsar >> Security Manager blocked access to eventBus on mod container. Cannot continue."); + } catch (ClassCastException cce) { + throw new RuntimeException("Pulsar >> Something in the mod container had the wrong type? " + cce.getMessage()); + } + } + + /** + * Internal (but public for EventBus use) handler for events. + * + * DO NOT CALL THIS DIRECTLY! Let EventBus handle it. + * + * @param evt An event object. + */ + @Subscribe + public void propagateEvent(Object evt) { + if (evt instanceof FMLPreInitializationEvent) preInit((FMLPreInitializationEvent) evt); + // We use individual buses due to the EventBus class using a Set rather than a List, thus losing the ordering. + // This trick is shamelessly borrowed from FML. + flightpath.post(evt); + } + + private boolean getEnabledFromConfig(PulseMeta meta) { + if (meta.isForced() || !useConfig) return true; // Forced or no config set. + + return conf.isModuleEnabled(meta); + } + + private void preInit(FMLPreInitializationEvent evt) { + if (!blockNewRegistrations) conf.flush(); // First preInit call, so flush config + blockNewRegistrations = true; + } + + private boolean hasRequiredPulses(Map.Entry entry) { + String deps = entry.getKey().getClass().getAnnotation(Pulse.class).pulsesRequired(); + if (!deps.equals("")) { + String[] parsedDeps = deps.split(";"); + for (String s : parsedDeps) { + if (!isPulseLoaded(s)) { + log.info("Skipping Pulse " + entry.getValue().getId() + "; missing pulse: " + s); + return false; + } + } + } + return true; + } + + /** + * Check if a given Pulse ID is loaded in this manager. + * + * @param pulseId The ID to check. + * @return Whether the ID was present. + */ + public boolean isPulseLoaded(String pulseId) { + for(Map.Entry entry : pulses.entrySet()) { + if (entry.getValue().getId().equals(pulseId)) { + return true; + } + } + return false; + } + + public Collection getAllPulseMetadata() { + return pulses.values(); + } + + @Override + public String toString() { + return "PulseManager[" + id + "]"; + } +} diff --git a/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java b/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java new file mode 100644 index 0000000..aa74275 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/debug/EventSpy.java @@ -0,0 +1,28 @@ +package slimeknights.mantle.pulsar.debug; + +import com.google.common.eventbus.Subscribe; + +import net.minecraftforge.fml.common.Loader; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import slimeknights.mantle.pulsar.pulse.Pulse; + +/** + * Debug Pulse to 'eavesdrop' on the PulseManager event bus traffic. + * + * @author Arkan + */ +@SuppressWarnings("unused") +@Pulse(id="EventSpy", description="we iz in ur buses, monitorin ur eventz", forced=true) +public class EventSpy { + + private final Logger log = LogManager.getLogger("EventSpy/" + Loader.instance().activeModContainer().getModId()); + + @Subscribe + public void receive(Object evt) { + log.info("Received event: " + evt); + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java new file mode 100755 index 0000000..9299344 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/Airdrop.java @@ -0,0 +1,15 @@ +package slimeknights.mantle.pulsar.flightpath; + +import java.lang.annotation.*; + +/** + * Default annotation for Flightpath subscriptions. + * + * We don't use @Subscriber, as too many frameworks use it (which may lead to import hell) + * + * @author Arkan + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Airdrop {} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java new file mode 100755 index 0000000..909c39c --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/Flightpath.java @@ -0,0 +1,101 @@ +package slimeknights.mantle.pulsar.flightpath; + +import slimeknights.mantle.pulsar.flightpath.lib.AnnotationLocator; +import slimeknights.mantle.pulsar.flightpath.lib.BlackholeExceptionHandler; + +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * Flightpath - an ordered event bus implementation. + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +@SuppressWarnings({"unused","unchecked"}) +public class Flightpath { + + private final ISubscriberLocator locator; + // Note we *MUST* use a linked map, otherwise order is lost. + private final LinkedHashMap>> subscribers = new LinkedHashMap>>(); + // Anything that manipulates state *MUST* acquire this lock. It prevents awkward issues when iterating. + private final Object lock = new Object(); + + private IExceptionHandler exceptionHandler = new BlackholeExceptionHandler(); + + /** + * Generates a plain old Flightpath, using the default @Airdrop annotation. + */ + public Flightpath() { + this.locator = new AnnotationLocator(Airdrop.class); + } + + /** + * Generates a Flightpath using a different locator implementation. + * + * Pass a custom constructed instance of AnnotationLocator to use alternative annotations. + * + * @param locator The locator to be applied to new objects. + */ + public Flightpath(ISubscriberLocator locator) { + this.locator = locator; + } + + /** + * Used to change exception handling behaviour. + * + * @param handler The handler to use. + */ + public void setExceptionHandler(IExceptionHandler handler) { + synchronized (lock) { + this.exceptionHandler = handler; + } + } + + /** + * Registers a given object onto the bus. + * + * @param obj Object to attach to the bus. + */ + public void register(Object obj) { + synchronized (lock) { + if (subscribers.containsKey(obj)) return; // Nothing to do. + subscribers.put(obj, locator.findSubscribers(obj)); + } + } + + /** + * Posts the given event on the bus. + * + * By default this blackholes exceptions. If you need different behaviour, see setExceptionHandler. + * + * @param evt The event to post. + */ + public void post(Object evt) { + synchronized (lock) { + for (Map.Entry>> ent : subscribers.entrySet()) { + for (Map.Entry> objEnt: ent.getValue().entrySet()) { + if (!objEnt.getKey().isAssignableFrom(evt.getClass())) continue; + Set ms = objEnt.getValue(); + for (Method m : ms) { + try { + boolean access = m.isAccessible(); + m.setAccessible(true); + m.invoke(ent.getKey(), evt); + m.setAccessible(access); + } catch (Exception ex) { + exceptionHandler.handle(ex); + } + } + } + } + exceptionHandler.flush(); + } + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java new file mode 100755 index 0000000..782a05a --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/IExceptionHandler.java @@ -0,0 +1,25 @@ +package slimeknights.mantle.pulsar.flightpath; + +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * General interface for an exception handler. + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +public interface IExceptionHandler { + + /** + * Handle a given exception. + * + * @param ex The exception (duh) + */ + void handle(Exception ex); + + /** + * Called after all methods have been invoked for cleanup or coalescing. + */ + void flush(); + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java new file mode 100755 index 0000000..6129148 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/ISubscriberLocator.java @@ -0,0 +1,18 @@ +package slimeknights.mantle.pulsar.flightpath; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.reflect.Method; +import java.util.Map; +import java.util.Set; + +/** + * Interface for defining custom subscriber scanners. + */ +@ParametersAreNonnullByDefault +public interface ISubscriberLocator { + + @Nonnull + Map> findSubscribers(Object obj); + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java new file mode 100755 index 0000000..298fda2 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/AnnotationLocator.java @@ -0,0 +1,38 @@ +package slimeknights.mantle.pulsar.flightpath.lib; + +import slimeknights.mantle.pulsar.flightpath.ISubscriberLocator; + +import javax.annotation.Nonnull; +import javax.annotation.ParametersAreNonnullByDefault; +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.*; + +/** + * Default implementation of ISubscriberLocator + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +public class AnnotationLocator implements ISubscriberLocator { + + private final Class annotation; + + public AnnotationLocator(Class annotation) { + this.annotation = annotation; + } + + @Override + public @Nonnull Map> findSubscribers(Object obj) { + Map> methods = new HashMap>(); + for (Method m : obj.getClass().getMethods()) { + if (m.isAnnotationPresent(annotation) && m.getParameterTypes().length == 1) { + Class param = m.getParameterTypes()[0]; + if (!methods.containsKey(param)) methods.put(param, new HashSet()); + methods.get(param).add(m); + } + } + return methods; + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java new file mode 100755 index 0000000..60f5f1b --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/flightpath/lib/BlackholeExceptionHandler.java @@ -0,0 +1,25 @@ +package slimeknights.mantle.pulsar.flightpath.lib; + +import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; + +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Default exception handler when Flightpath has been asked to ignore errors. + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +public class BlackholeExceptionHandler implements IExceptionHandler { + + @Override + public void handle(Exception ex) { + // NO-OP + } + + @Override + public void flush() { + // NO-OP + } + +} diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java new file mode 100644 index 0000000..148456e --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/internal/BusExceptionHandler.java @@ -0,0 +1,40 @@ +package slimeknights.mantle.pulsar.internal; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import slimeknights.mantle.pulsar.flightpath.IExceptionHandler; + +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Custom exception catcher that logs events. + */ +@ParametersAreNonnullByDefault +public final class BusExceptionHandler implements IExceptionHandler { + + private final String id; + private final Logger logger; + + /** + * @param id Mod ID to include in exception raises. + */ + public BusExceptionHandler(String id) { + this.id = id; + this.logger = LogManager.getLogger(id + "-Pulsar-Flightpath"); + } + + @Override + public void handle(Exception ex) { + this.logger.error("Exception caught from a pulse on flightpath for mod ID " + id + ": ", ex); + if(ex instanceof RuntimeException) { + throw (RuntimeException)ex; + } + } + + @Override + public void flush() { + // NO-OP + } + +} diff --git a/src/mantle/pulsar/internal/Configuration.java b/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java similarity index 92% rename from src/mantle/pulsar/internal/Configuration.java rename to src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java index 5b243fb..78deff7 100644 --- a/src/mantle/pulsar/internal/Configuration.java +++ b/src/main/java/slimeknights/mantle/pulsar/internal/Configuration.java @@ -1,4 +1,4 @@ -package mantle.pulsar.internal; +package slimeknights.mantle.pulsar.internal; import java.io.*; import java.util.*; @@ -8,23 +8,28 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; -import cpw.mods.fml.common.Loader; -import mantle.pulsar.config.IConfiguration; -import mantle.pulsar.internal.logging.ILogger; -import mantle.pulsar.pulse.PulseMeta; +import net.minecraftforge.fml.common.Loader; + +import org.apache.logging.log4j.Logger; + +import slimeknights.mantle.pulsar.config.IConfiguration; +import slimeknights.mantle.pulsar.pulse.PulseMeta; + +import javax.annotation.ParametersAreNonnullByDefault; /** * Default Gson Configuration helper. * * @author Arkan */ +@ParametersAreNonnullByDefault public class Configuration implements IConfiguration { private static final int CONFIG_LEVEL = 1; private static final Gson gson = new GsonBuilder().setPrettyPrinting().create(); private final String confPath; - private final ILogger logger; + private final Logger logger; private Map modules; @@ -36,7 +41,7 @@ public class Configuration implements IConfiguration { * @param confName The config file name (without path or .json suffix) * @param logger The logger to send debug info to. */ - public Configuration(String confName, ILogger logger) { + public Configuration(String confName, Logger logger) { this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".json"; this.logger = logger; } @@ -50,7 +55,7 @@ public class Configuration implements IConfiguration { public boolean isModuleEnabled(PulseMeta meta) { ConfigEntry entry = modules.get(meta.getId()); if (entry == null) { - modules.put(meta.getId(), new ConfigEntry(meta.isEnabled(), meta.getDescription())); + modules.put(meta.getId(), new ConfigEntry(meta.isDefaultEnabled(), meta.getDescription())); return meta.isEnabled(); } else { return entry.getEnabled(); diff --git a/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java b/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java new file mode 100644 index 0000000..c45b4e9 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/internal/CrashHandler.java @@ -0,0 +1,49 @@ +package slimeknights.mantle.pulsar.internal; + +import net.minecraftforge.fml.common.ICrashCallable; +import slimeknights.mantle.pulsar.control.PulseManager; +import slimeknights.mantle.pulsar.pulse.PulseMeta; + +/** + * FML crash callable for Pulse Managers; dumps a list of loaded pulses to the error log. + * + * @author Arkan + */ +public class CrashHandler implements ICrashCallable { + + private String id; + private PulseManager manager; + + public CrashHandler(String modId, PulseManager manager) { + this.id = "Pulsar/" + modId + " loaded Pulses"; + this.manager = manager; + } + + @Override + public String getLabel() { + return id; + } + + @Override + public String call() throws Exception { + String out = "\n"; + for (PulseMeta meta : manager.getAllPulseMetadata()) { + String state = getStateFromMeta(meta); + out += "\t\t- " + meta.getId() + " (" + state + ")\n"; // Yes, yes, manual indenting, I know... + } + return out; + } + + private static String getStateFromMeta(PulseMeta meta) { + if (meta.isForced()) { + return "Enabled/Forced"; + } else { + if (meta.isEnabled()) { + return "Enabled/Not Forced"; + } else { + return "Disabled/Not Forced"; + } + } + } + +} diff --git a/src/mantle/pulsar/package-info.java b/src/main/java/slimeknights/mantle/pulsar/package-info.java similarity index 97% rename from src/mantle/pulsar/package-info.java rename to src/main/java/slimeknights/mantle/pulsar/package-info.java index 8c4fa42..d3b6f3e 100644 --- a/src/mantle/pulsar/package-info.java +++ b/src/main/java/slimeknights/mantle/pulsar/package-info.java @@ -33,4 +33,4 @@ * * @author Arkan */ -package mantle.pulsar; \ No newline at end of file +package slimeknights.mantle.pulsar; \ No newline at end of file diff --git a/src/mantle/pulsar/pulse/Pulse.java b/src/main/java/slimeknights/mantle/pulsar/pulse/Pulse.java similarity index 82% rename from src/mantle/pulsar/pulse/Pulse.java rename to src/main/java/slimeknights/mantle/pulsar/pulse/Pulse.java index 8d4f17c..f8317b4 100644 --- a/src/mantle/pulsar/pulse/Pulse.java +++ b/src/main/java/slimeknights/mantle/pulsar/pulse/Pulse.java @@ -1,10 +1,13 @@ -package mantle.pulsar.pulse; +package slimeknights.mantle.pulsar.pulse; import java.lang.annotation.*; /** * Metadata annotation for IPulse implementations. * + * Pulses should use the standard Google Event Bus @Subscribe annotation to catch FML events, which are forwarded from + * the current mod container (including Pre/Init/Post events). + * * @author Arkan */ @Retention(RetentionPolicy.RUNTIME) diff --git a/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java b/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java new file mode 100644 index 0000000..81fc979 --- /dev/null +++ b/src/main/java/slimeknights/mantle/pulsar/pulse/PulseMeta.java @@ -0,0 +1,53 @@ +package slimeknights.mantle.pulsar.pulse; + +import javax.annotation.Nullable; +import javax.annotation.ParametersAreNonnullByDefault; + +/** + * Metadata wrapper for parsed @Pulse metadata. + * + * @author Arkan + */ +@ParametersAreNonnullByDefault +public class PulseMeta { + + private String id, description; + private boolean forced, enabled, defaultEnabled; + private boolean missingDeps = false; + + public PulseMeta(String id, @Nullable String description, boolean forced, boolean enabled, boolean defaultEnabled) { + this.id = id; + this.description = description; + this.forced = forced; + this.enabled = enabled; + this.defaultEnabled = defaultEnabled; + } + + public String getId() { + return id; + } + + public String getDescription() { + return description; + } + + public boolean isForced() { + return !missingDeps && forced; + } + + public boolean isEnabled() { + return !missingDeps && enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public void setMissingDeps(boolean missing) { + missingDeps = missing; + } + + public boolean isDefaultEnabled() { + return defaultEnabled; + } +} diff --git a/src/main/java/slimeknights/mantle/tileentity/TileInventory.java b/src/main/java/slimeknights/mantle/tileentity/TileInventory.java new file mode 100644 index 0000000..f64df61 --- /dev/null +++ b/src/main/java/slimeknights/mantle/tileentity/TileInventory.java @@ -0,0 +1,261 @@ +package slimeknights.mantle.tileentity; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.ChatComponentText; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.util.IChatComponent; + +import java.util.Arrays; + +// Updated version of InventoryLogic in Mantle. Also contains a few bugfixes +public class TileInventory extends TileEntity implements IInventory { + + private ItemStack[] inventory; + protected String inventoryTitle; + protected boolean hasCustomName; + protected int stackSizeLimit; + + /** + * @param name Localization String for the inventory title. Can be overridden through setCustomName + */ + public TileInventory(String name, int inventorySize) { + this(name, inventorySize, 64); + } + + /** + * @param name Localization String for the inventory title. Can be overridden through setCustomName + */ + public TileInventory(String name, int inventorySize, int maxStackSize) { + this.inventory = new ItemStack[inventorySize]; + this.stackSizeLimit = maxStackSize; + this.inventoryTitle = name; + } + + /* Inventory management */ + + @Override + public ItemStack getStackInSlot(int slot) { + if(slot < 0 || slot >= inventory.length) { + return null; + } + + return inventory[slot]; + } + + public boolean isStackInSlot(int slot) { + return getStackInSlot(slot) != null; + } + + public void resize(int size) { + inventory = Arrays.copyOf(inventory, size); + } + + @Override + public int getSizeInventory() { + return inventory.length; + } + + @Override + public int getInventoryStackLimit() { + return stackSizeLimit; + } + + @Override + public void setInventorySlotContents(int slot, ItemStack itemstack) { + if(slot < 0 || slot >= inventory.length) { + return; + } + + inventory[slot] = itemstack; + if(itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { + itemstack.stackSize = getInventoryStackLimit(); + } + } + + @Override + public ItemStack decrStackSize(int slot, int quantity) { + ItemStack itemStack = getStackInSlot(slot); + + if(itemStack == null) { + return null; + } + + // whole itemstack taken out + if(itemStack.stackSize <= quantity) { + setInventorySlotContents(slot, null); + this.markDirty(); + return itemStack; + } + + // split itemstack + itemStack = itemStack.splitStack(quantity); + // slot is empty, set to null + if(getStackInSlot(slot).stackSize == 0) { + setInventorySlotContents(slot, null); + } + + this.markDirty(); + // return remainder + return itemStack; + } + + @Override + public ItemStack removeStackFromSlot(int slot) { + ItemStack itemStack = getStackInSlot(slot); + setInventorySlotContents(slot, null); + return itemStack; + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack itemstack) { + if(slot < getSizeInventory()) { + if(inventory[slot] == null || itemstack.stackSize + inventory[slot].stackSize <= getInventoryStackLimit()) { + return true; + } + } + return false; + } + + @Override + public void clear() { + for(int i = 0; i < inventory.length; i++) { + inventory[i] = null; + } + } + + @Override + public String getName() { + return this.inventoryTitle; + } + + @Override + public boolean hasCustomName() { + return this.hasCustomName; + } + + public void setCustomName(String customName) { + this.hasCustomName = true; + this.inventoryTitle = customName; + } + + @Override + public IChatComponent getDisplayName() { + if(hasCustomName()) { + return new ChatComponentText(getName()); + } + + return new ChatComponentTranslation(getName()); + } + + + /* Supporting methods */ + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + // block changed/got broken? + if(worldObj.getTileEntity(pos) != this || worldObj.getBlockState(pos).getBlock() == Blocks.air) { + return false; + } + + return + entityplayer.getDistanceSq((double) pos.getX() + 0.5D, (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D) + <= 64D; + } + + @Override + public void openInventory(EntityPlayer player) { + + } + + @Override + public void closeInventory(EntityPlayer player) { + + } + + /* NBT */ + @Override + public void readFromNBT(NBTTagCompound tags) { + super.readFromNBT(tags); + readInventoryFromNBT(tags); + } + + public void readInventoryFromNBT(NBTTagCompound tags) { + super.readFromNBT(tags); + + this.resize(tags.getInteger("InventorySize")); + + readInventoryFromNBT(this, tags); + + if(tags.hasKey("CustomName", 8)) { + this.inventoryTitle = tags.getString("CustomName"); + } + } + + @Override + public void writeToNBT(NBTTagCompound tags) { + super.writeToNBT(tags); + + tags.setInteger("InventorySize", inventory.length); + + writeInventoryToNBT(this, tags); + + if(this.hasCustomName()) { + tags.setString("CustomName", this.inventoryTitle); + } + } + + /** Writes the contents of the inventory to the tag */ + public static void writeInventoryToNBT(IInventory inventory, NBTTagCompound tag) { + NBTTagList nbttaglist = new NBTTagList(); + + for(int i = 0; i < inventory.getSizeInventory(); i++) { + if(inventory.getStackInSlot(i) != null) { + NBTTagCompound itemTag = new NBTTagCompound(); + itemTag.setByte("Slot", (byte) i); + inventory.getStackInSlot(i).writeToNBT(itemTag); + nbttaglist.appendTag(itemTag); + } + } + + tag.setTag("Items", nbttaglist); + } + + /** Reads a an inventory from the tag. Overwrites current content */ + public static void readInventoryFromNBT(IInventory inventory, NBTTagCompound tag) { + NBTTagList nbttaglist = tag.getTagList("Items", 10); + + for(int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound itemTag = nbttaglist.getCompoundTagAt(i); + int slot = itemTag.getByte("Slot") & 255; + + if(slot >= 0 && slot < inventory.getSizeInventory()) { + inventory.setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(itemTag)); + } + } + } + + /* Default implementations of hardly used methods */ + public ItemStack getStackInSlotOnClosing(int slot) { + return null; + } + + @Override + public int getField(int id) { + return 0; + } + + @Override + public void setField(int id, int value) { + + } + + @Override + public int getFieldCount() { + return 0; + } +} diff --git a/src/main/java/slimeknights/mantle/util/LocUtils.java b/src/main/java/slimeknights/mantle/util/LocUtils.java new file mode 100644 index 0000000..42f55a6 --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/LocUtils.java @@ -0,0 +1,21 @@ +package slimeknights.mantle.util; + +import net.minecraft.util.StatCollector; + +import java.util.Locale; + +// localization utils +public abstract class LocUtils { + private LocUtils() {} + + /** + * Removes all whitespaces from the string and makes it lowercase. + */ + public static String makeLocString(String unclean) { + return unclean.toLowerCase(Locale.US).replaceAll(" ", ""); + } + + public static String translateRecursive(String key, Object... params) { + return StatCollector.translateToLocal(StatCollector.translateToLocalFormatted(key, params)); + } +} diff --git a/src/main/java/slimeknights/mantle/util/RecipeMatch.java b/src/main/java/slimeknights/mantle/util/RecipeMatch.java new file mode 100644 index 0000000..f6651ba --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/RecipeMatch.java @@ -0,0 +1,294 @@ +package slimeknights.mantle.util; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraftforge.oredict.OreDictionary; + +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import slimeknights.mantle.Mantle; + +/** + * Utility class that allows to find a specific subset of items in a list of itemstacks. + * Matches can be found through oredictionary, simple nbt-independant item-meta combinations etc. + * + * The match returned by this class can then be used to remove the found recipe match from the items. + */ +public abstract class RecipeMatch { + + public final int amountNeeded; + public final int amountMatched; + + /** + * @param amountNeeded How many of the itemstack are needed for the match + * @param amountMatched If amount needed itemstacks are present, as how many matches does this count? + */ + public RecipeMatch(int amountMatched, int amountNeeded) { + this.amountMatched = amountMatched; + this.amountNeeded = amountNeeded; + } + + /** + * Return all possible inputs that are a single item, if applicable. + */ + public abstract List getInputs(); + + public abstract Match matches(ItemStack[] stacks); + + public static RecipeMatch of(String oredict) { + return of(oredict, 1); + } + + public static RecipeMatch of(String oredict, int matched) { + return of(oredict, 1, matched); + } + + public static RecipeMatch of(String oredict, int amount, int matched) { + return new RecipeMatch.Oredict(oredict, amount, matched); + } + + public static RecipeMatch of(List oredict) { + return of(oredict, 1); + } + + public static RecipeMatch of(List oredict, int matched) { + return of(oredict, 1, matched); + } + + public static RecipeMatch of(List oredict, int amount, int matched) { + return new RecipeMatch.Oredict(oredict, amount, matched); + } + + public static RecipeMatch of(net.minecraft.item.Item item) { + return of(item, 1); + } + + public static RecipeMatch of(net.minecraft.item.Item item, int matched) { + return of(item, 1, matched); + } + + public static RecipeMatch of(net.minecraft.item.Item item, int amount, int matched) { + return new RecipeMatch.Item(new ItemStack(item), amount, matched); + } + + public static RecipeMatch of(Block block) { + return of(block, 1); + } + + public static RecipeMatch of(Block block, int matched) { + return of(block, 1, matched); + } + + public static RecipeMatch of(Block block, int amount, int matched) { + return new RecipeMatch.Item(new ItemStack(block), amount, matched); + } + + public static RecipeMatch ofNBT(ItemStack stack) { + return ofNBT(stack, 1); + } + + public static RecipeMatch ofNBT(ItemStack stack, int matched) { + return new RecipeMatch.ItemCombination(matched, stack); + } + + /** Removes the match from the stacks */ + public static void removeMatch(ItemStack[] stacks, Match match) { + for(ItemStack stack : match.stacks) { + for(int i = 0; i < stacks.length; i++) { + // nbt sensitive since toolparts etc. use nbt + if(ItemStack.areItemsEqual(stack, stacks[i]) && ItemStack.areItemStackTagsEqual(stack, stacks[i])) { + if(stacks[i].stackSize < stack.stackSize) { + Mantle.logger.error("RecipeMatch has incorrect stacksize! {}", stacks[i].toString()); + } + else { + stacks[i].stackSize -= stack.stackSize; + if(stacks[i].stackSize == 0) { + stacks[i] = null; + } + } + break; + } + } + } + } + + /** A specific amount of a certain item is needed. Supports wildcard-metadata. Not NBT sensitive. */ + public static class Item extends RecipeMatch { + + private final ItemStack template; + + public Item(ItemStack template, int amountNeeded) { + this(template, amountNeeded, 1); + } + + /** + * @param template The itemstack to match + * @param amountNeeded How many of the itemstack are needed for the match + * @param amountMatched If amountneeded itemstacks are present, as how many matches does this count? + */ + public Item(ItemStack template, int amountNeeded, int amountMatched) { + super(amountMatched, amountNeeded); + this.template = template; + } + + @Override + public List getInputs() { + return ImmutableList.of(template); + } + + @Override + public Match matches(ItemStack[] stacks) { + List found = Lists.newLinkedList(); + int stillNeeded = amountNeeded; + + for(ItemStack stack : stacks) { + if(OreDictionary.itemMatches(template, stack, false)) { + // add the amount found to the list + ItemStack copy = stack.copy(); + copy.stackSize = Math.min(copy.stackSize, stillNeeded); + found.add(copy); + stillNeeded -= copy.stackSize; + + // we found enough + if(stillNeeded <= 0) { + return new Match(found, amountMatched); + } + } + } + + return null; + } + } + + /** A combination of multiple items. NBT SENSITIVE! */ + public static class ItemCombination extends RecipeMatch { + + protected final ItemStack[] itemStacks; + + /** + * @param amountMatched If amount needed itemstacks are present, as how many matches does this count? + */ + public ItemCombination(int amountMatched, ItemStack... stacks) { + super(amountMatched, 0); + + this.itemStacks = stacks; + } + + @Override + public List getInputs() { + if(itemStacks.length == 0 || itemStacks.length > 1) { + return ImmutableList.of(); + } + return ImmutableList.of(itemStacks[0]); + } + + @Override + public Match matches(ItemStack[] stacks) { + List found = Lists.newLinkedList(); + Set needed = Sets.newHashSet(); + + for(int i = 0; i < itemStacks.length; i++) { + if(itemStacks[i] != null) { + needed.add(i); + } + } + + for(ItemStack stack : stacks) { + Iterator iter = needed.iterator(); + while(iter.hasNext()) { + int index = iter.next(); + ItemStack template = itemStacks[index]; + if(ItemStack.areItemsEqual(template, stack) && ItemStack.areItemStackTagsEqual(template, stack)) { + // add the amount found to the list + ItemStack copy = stack.copy(); + copy.stackSize = 1; + found.add(copy); + iter.remove(); + break; + } + } + } + + if(needed.isEmpty()) { + return new Match(found, amountMatched); + } + return null; + } + } + + /** A specific amount of an oredicted material is needed to match. */ + public static class Oredict extends RecipeMatch { + + private final List oredictEntry; // todo: change this to the actual list in the oredict + + public Oredict(List oredictEntry, int amountNeeded) { + this(oredictEntry, amountNeeded, 1); + } + + public Oredict(List oredictEntry, int amountNeeded, int amountMatched) { + super(amountMatched, amountNeeded); + this.oredictEntry = oredictEntry; + } + + public Oredict(String oredictEntry, int amountNeeded) { + this(oredictEntry, amountNeeded, 1); + } + + public Oredict(String oredictEntry, int amountNeeded, int amountMatched) { + super(amountMatched, amountNeeded); + this.oredictEntry = OreDictionary.getOres(oredictEntry); + } + + @Override + public List getInputs() { + return oredictEntry; + } + + @Override + public Match matches(ItemStack[] stacks) { + List found = Lists.newLinkedList(); + int stillNeeded = amountNeeded; + + for(ItemStack ore : oredictEntry) { + for(ItemStack stack : stacks) { + if(OreDictionary.itemMatches(ore, stack, false)) { + // add the amount found to the list + ItemStack copy = stack.copy(); + copy.stackSize = Math.min(copy.stackSize, stillNeeded); + found.add(copy); + stillNeeded -= copy.stackSize; + + // we found enough + if(stillNeeded <= 0) { + return new Match(found, amountMatched); + } + } + } + } + + return null; + } + } + + /** Represents a collection of items that match the recipies */ + public static class Match { + + /** The stacks that have to be removed to apply this match */ + public List stacks; + + /** How often the recipe is found within this match */ + public int amount; + + public Match(List stacks, int amount) { + this.stacks = stacks; + this.amount = amount; + } + } +} diff --git a/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java b/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java new file mode 100644 index 0000000..8d8daf6 --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/RecipeMatchRegistry.java @@ -0,0 +1,133 @@ +package slimeknights.mantle.util; + +import com.google.common.collect.Lists; + +import net.minecraft.block.Block; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import java.util.Collection; +import java.util.List; + +/** + * Contains a set of matches. Allows you to easily find if a set of itemstacks matches one of them. + */ +// MANTLE +public class RecipeMatchRegistry { + + protected final List items = Lists.newArrayList(); + + public RecipeMatch.Match matches(Collection stacks) { + return matches(stacks.toArray(new ItemStack[stacks.size()])); + } + + // looks for a match in the given itemstacks + public RecipeMatch.Match matches(ItemStack... stacks) { + for(RecipeMatch recipe : items) { + RecipeMatch.Match match = recipe.matches(stacks); + if(match != null) { + return match; + } + } + + return null; + } + + // looks for a match with at least the given amount in the given itemstacks + public RecipeMatch.Match matches(ItemStack[] stacks, int minAmount) { + stacks = copyItemStackArray(stacks); // copy so we don't modify original + + List matches = Lists.newLinkedList(); + + RecipeMatch.Match match; + int sum = 0; + while(sum < minAmount && (match = matches(stacks)) != null) { + matches.add(match); + RecipeMatch.removeMatch(stacks, match); + + sum += match.amount; + } + + // not enough found + if(sum < minAmount) { + return null; + } + + // merge all found matches into one match + List foundStacks = Lists.newLinkedList(); + for(RecipeMatch.Match m : matches) { + foundStacks.addAll(m.stacks); + } + + return new RecipeMatch.Match(foundStacks, sum); + } + + /** + * Associates an oredict entry with this material. Used for repairing and other. + * + * @param oredictItem Oredict-String + * @param amountNeeded How many of this item are needed to count as one full material item. + * @param amountMatched If both item and amount are present, how often did they match? + */ + public void addItem(String oredictItem, int amountNeeded, int amountMatched) { + items.add(new RecipeMatch.Oredict(oredictItem, amountNeeded, amountMatched)); + } + + public void addItem(String oredictItem) { + addItem(oredictItem, 1, 1); + } + + /** + * Associates a block with this material. Used for repairing and other. + * + * @param amountMatched For how many matches the block counts (e.g. redstone dust = 1 match, Redstone block = 9) + */ + public void addItem(Block block, int amountMatched) { + items.add(new RecipeMatch.Item(new ItemStack(block), 1, amountMatched)); + } + + /** + * Associates an item entry with this material. Used for repairing and other. + * + * @param item The item + * @param amountNeeded How many of this item are needed to count as one full material item. + * @param amountMatched If both item and amount are present, how often did they match? + */ + public void addItem(Item item, int amountNeeded, int amountMatched) { + items.add(new RecipeMatch.Item(new ItemStack(item), amountNeeded, amountMatched)); + } + + /** + * Associates an item entry with this material. Used for repairing and other. + * + * @param item The item + * @param amountNeeded How many of this item are needed to count as one full material item. + * @param amountMatched If both item and amount are present, how often did they match? + */ + public void addItem(ItemStack item, int amountNeeded, int amountMatched) { + items.add(new RecipeMatch.Item(item, amountNeeded, amountMatched)); + } + + /** + * Associates an item with this material. Used for repairing and other. + */ + public void addItem(Item item) { + addItem(item, 1, 1); + } + + public void addRecipeMatch(RecipeMatch match) { + items.add(match); + } + + + public static ItemStack[] copyItemStackArray(ItemStack[] in) { + ItemStack[] stacksCopy = new ItemStack[in.length]; + for(int i = 0; i < in.length; i++) { + if(in[i] != null) { + stacksCopy[i] = in[i].copy(); + } + } + + return stacksCopy; + } +} diff --git a/src/mantle/utils/RecipeRemover.java b/src/main/java/slimeknights/mantle/util/RecipeRemover.java similarity index 85% rename from src/mantle/utils/RecipeRemover.java rename to src/main/java/slimeknights/mantle/util/RecipeRemover.java index 3ddbef9..c681589 100644 --- a/src/mantle/utils/RecipeRemover.java +++ b/src/main/java/slimeknights/mantle/util/RecipeRemover.java @@ -1,4 +1,4 @@ -package mantle.utils; +package slimeknights.mantle.util; import java.util.List; import java.util.Map; @@ -15,13 +15,15 @@ import net.minecraftforge.common.ChestGenHooks; @SuppressWarnings("unchecked") public class RecipeRemover { - public static void removeShapedRecipes (List removelist) + public static void removeShapedRecipes(List removelist) { for (ItemStack stack : removelist) + { removeShapedRecipe(stack); + } } - public static void removeAnyRecipe (ItemStack resultItem) + public static void removeAnyRecipe(ItemStack resultItem) { List recipes = CraftingManager.getInstance().getRecipeList(); for (int i = 0; i < recipes.size(); i++) @@ -35,7 +37,7 @@ public class RecipeRemover } } - public static void removeShapedRecipe (ItemStack resultItem) + public static void removeShapedRecipe(ItemStack resultItem) { List recipes = CraftingManager.getInstance().getRecipeList(); for (int i = 0; i < recipes.size(); i++) @@ -54,7 +56,7 @@ public class RecipeRemover } } - public static void removeShapelessRecipe (ItemStack resultItem) + public static void removeShapelessRecipe(ItemStack resultItem) { List recipes = CraftingManager.getInstance().getRecipeList(); for (int i = 0; i < recipes.size(); i++) @@ -73,24 +75,24 @@ public class RecipeRemover } } - public static void removeFurnaceRecipe (ItemStack resultItem) + public static void removeFurnaceRecipe(ItemStack resultItem) { Map recipes = FurnaceRecipes.instance().getSmeltingList(); recipes.remove(resultItem); } - public static void removeFurnaceRecipe (Item i, int metadata) + public static void removeFurnaceRecipe(Item i, int metadata) { removeFurnaceRecipe(new ItemStack(i, 1, metadata)); } - public static void removeFurnaceRecipe (Item i) + public static void removeFurnaceRecipe(Item i) { removeFurnaceRecipe(new ItemStack(i, 1, 32767)); } //removes from all vanilla worldgen chests :D - public static void removeFromChests (ItemStack resultItem) + public static void removeFromChests(ItemStack resultItem) { ChestGenHooks.getInfo(ChestGenHooks.BONUS_CHEST).removeItem(resultItem); ChestGenHooks.getInfo(ChestGenHooks.VILLAGE_BLACKSMITH).removeItem(resultItem); diff --git a/src/main/java/slimeknights/mantle/util/SlimeknightException.java b/src/main/java/slimeknights/mantle/util/SlimeknightException.java new file mode 100644 index 0000000..58b35ca --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/SlimeknightException.java @@ -0,0 +1,27 @@ +package slimeknights.mantle.util; + +public class SlimeknightException extends RuntimeException { + + public SlimeknightException() { + } + + public SlimeknightException(String message) { + super(message); + } + + public SlimeknightException(String message, Object... params) { + super(String.format(message, params)); + } + + public SlimeknightException(String message, Throwable cause) { + super(message, cause); + } + + public SlimeknightException(Throwable cause) { + super(cause); + } + + public SlimeknightException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/src/main/java/slimeknights/mantle/util/TagHelper.java b/src/main/java/slimeknights/mantle/util/TagHelper.java new file mode 100644 index 0000000..3151e53 --- /dev/null +++ b/src/main/java/slimeknights/mantle/util/TagHelper.java @@ -0,0 +1,40 @@ +package slimeknights.mantle.util; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.nbt.NBTTagString; + +public class TagHelper { + public static int TAG_TYPE_STRING = (new NBTTagString()).getId(); + public static int TAG_TYPE_COMPOUND = (new NBTTagCompound()).getId(); + + private TagHelper() { + } + + /* Generic Tag Operations */ + public static NBTTagCompound getTagSafe(ItemStack stack) { + if(stack == null || stack.getItem() == null || !stack.hasTagCompound()) { + return new NBTTagCompound(); + } + + return stack.getTagCompound(); + } + + public static NBTTagCompound getTagSafe(NBTTagCompound tag, String key) { + if(tag == null || !tag.hasKey(key)) { + return new NBTTagCompound(); + } + + return tag.getCompoundTag(key); + } + + public static NBTTagList getTagListSafe(NBTTagCompound tag, String key, int type) { + if(tag == null || !tag.hasKey(key)) { + return new NBTTagList(); + } + + return tag.getTagList(key, type); + } + +} diff --git a/src/main/resources/META-INF/Mantle_at.cfg b/src/main/resources/META-INF/Mantle_at.cfg new file mode 100644 index 0000000..c92f814 --- /dev/null +++ b/src/main/resources/META-INF/Mantle_at.cfg @@ -0,0 +1,11 @@ +# Mantle -- Access Transformer + +# GuiContainer +public net.minecraft.client.gui.inventory.GuiContainer field_146999_f #xSize +public net.minecraft.client.gui.inventory.GuiContainer field_147000_g #ySize +public net.minecraft.client.gui.inventory.GuiContainer field_147009_r #guiTop +public net.minecraft.client.gui.inventory.GuiContainer field_147003_i #guiLeft +public net.minecraft.client.gui.inventory.GuiContainer func_146977_a(Lnet/minecraft/inventory/Slot;)V #renderSlot +public net.minecraft.client.gui.inventory.GuiContainer func_146981_a(Lnet/minecraft/inventory/Slot;II)Z #isMouseOverSlot +# GuiScreen +public net.minecraft.client.gui.GuiScreen field_146292_n #buttonList diff --git a/resources/Mantle.png b/src/main/resources/Mantle.png similarity index 100% rename from resources/Mantle.png rename to src/main/resources/Mantle.png diff --git a/resources/assets/mantle/manuals/test.xml b/src/main/resources/assets/mantle/manuals/test.xml similarity index 100% rename from resources/assets/mantle/manuals/test.xml rename to src/main/resources/assets/mantle/manuals/test.xml diff --git a/src/main/resources/assets/mantle/models/item/mantleBook.json b/src/main/resources/assets/mantle/models/item/mantleBook.json new file mode 100644 index 0000000..83eecc5 --- /dev/null +++ b/src/main/resources/assets/mantle/models/item/mantleBook.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "mantle:items/mantlebook_blue" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -3 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/resources/assets/mantle/textures/gui/book.png b/src/main/resources/assets/mantle/textures/gui/book.png similarity index 100% rename from resources/assets/mantle/textures/gui/book.png rename to src/main/resources/assets/mantle/textures/gui/book.png diff --git a/resources/assets/mantle/textures/gui/bookcrafting.png b/src/main/resources/assets/mantle/textures/gui/bookcrafting.png similarity index 100% rename from resources/assets/mantle/textures/gui/bookcrafting.png rename to src/main/resources/assets/mantle/textures/gui/bookcrafting.png diff --git a/resources/assets/mantle/textures/gui/bookfurnace.png b/src/main/resources/assets/mantle/textures/gui/bookfurnace.png similarity index 100% rename from resources/assets/mantle/textures/gui/bookfurnace.png rename to src/main/resources/assets/mantle/textures/gui/bookfurnace.png diff --git a/resources/assets/mantle/textures/gui/bookleft.png b/src/main/resources/assets/mantle/textures/gui/bookleft.png similarity index 100% rename from resources/assets/mantle/textures/gui/bookleft.png rename to src/main/resources/assets/mantle/textures/gui/bookleft.png diff --git a/resources/assets/mantle/textures/gui/bookright.png b/src/main/resources/assets/mantle/textures/gui/bookright.png similarity index 100% rename from resources/assets/mantle/textures/gui/bookright.png rename to src/main/resources/assets/mantle/textures/gui/bookright.png diff --git a/resources/assets/mantle/textures/gui/missingno.png b/src/main/resources/assets/mantle/textures/gui/missingno.png similarity index 100% rename from resources/assets/mantle/textures/gui/missingno.png rename to src/main/resources/assets/mantle/textures/gui/missingno.png diff --git a/resources/assets/mantle/textures/gui/tinkerbook_blue.png b/src/main/resources/assets/mantle/textures/gui/tinkerbook_blue.png similarity index 100% rename from resources/assets/mantle/textures/gui/tinkerbook_blue.png rename to src/main/resources/assets/mantle/textures/gui/tinkerbook_blue.png diff --git a/resources/assets/mantle/textures/gui/tinkerbook_green.png b/src/main/resources/assets/mantle/textures/gui/tinkerbook_green.png similarity index 100% rename from resources/assets/mantle/textures/gui/tinkerbook_green.png rename to src/main/resources/assets/mantle/textures/gui/tinkerbook_green.png diff --git a/resources/assets/mantle/textures/items/mantlebook_blue.png b/src/main/resources/assets/mantle/textures/items/mantlebook_blue.png similarity index 100% rename from resources/assets/mantle/textures/items/mantlebook_blue.png rename to src/main/resources/assets/mantle/textures/items/mantlebook_blue.png diff --git a/resources/assets/mantle/textures/items/tinkerbook_blue.png b/src/main/resources/assets/mantle/textures/items/tinkerbook_blue.png similarity index 100% rename from resources/assets/mantle/textures/items/tinkerbook_blue.png rename to src/main/resources/assets/mantle/textures/items/tinkerbook_blue.png diff --git a/resources/assets/mantle/textures/items/tinkerbook_diary.png b/src/main/resources/assets/mantle/textures/items/tinkerbook_diary.png similarity index 100% rename from resources/assets/mantle/textures/items/tinkerbook_diary.png rename to src/main/resources/assets/mantle/textures/items/tinkerbook_diary.png diff --git a/resources/assets/mantle/textures/items/tinkerbook_green.png b/src/main/resources/assets/mantle/textures/items/tinkerbook_green.png similarity index 100% rename from resources/assets/mantle/textures/items/tinkerbook_green.png rename to src/main/resources/assets/mantle/textures/items/tinkerbook_green.png diff --git a/resources/assets/mantle/textures/items/tinkerbook_smeltery.png b/src/main/resources/assets/mantle/textures/items/tinkerbook_smeltery.png similarity index 100% rename from resources/assets/mantle/textures/items/tinkerbook_smeltery.png rename to src/main/resources/assets/mantle/textures/items/tinkerbook_smeltery.png diff --git a/resources/assets/mantle/textures/items/tinkerbook_toolstation.png b/src/main/resources/assets/mantle/textures/items/tinkerbook_toolstation.png similarity index 100% rename from resources/assets/mantle/textures/items/tinkerbook_toolstation.png rename to src/main/resources/assets/mantle/textures/items/tinkerbook_toolstation.png diff --git a/resources/mcmod.info b/src/main/resources/mcmod.info similarity index 95% rename from resources/mcmod.info rename to src/main/resources/mcmod.info index de04bf5..3ff46cc 100644 --- a/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -1,5 +1,5 @@ [{ - "modid": "Mantle", + "modid": "mantle", "name": "Mantle", "description": "Shared code for Slime Knights mods and others.", "version": "${version}", diff --git a/src/mantle/Mantle.java b/src/mantle/Mantle.java deleted file mode 100644 index 7233f11..0000000 --- a/src/mantle/Mantle.java +++ /dev/null @@ -1,120 +0,0 @@ -package mantle; - -import static mantle.lib.CoreRepo.logger; -import static mantle.lib.CoreRepo.modId; -import static mantle.lib.CoreRepo.modName; -import static mantle.lib.CoreRepo.modVersion; - -import cpw.mods.fml.common.event.FMLServerStartedEvent; -import mantle.books.BookData; -import mantle.books.BookDataStore; -import mantle.common.IDDumps; -import mantle.common.MProxyCommon; -import mantle.items.Manual; -import mantle.lib.CoreConfig; -import mantle.lib.CoreRepo; -import mantle.lib.environment.EnvironmentChecks; -import cpw.mods.fml.common.Mod; -import cpw.mods.fml.common.Mod.EventHandler; -import cpw.mods.fml.common.Mod.Instance; -import cpw.mods.fml.common.SidedProxy; -import cpw.mods.fml.common.event.FMLInitializationEvent; -import cpw.mods.fml.common.event.FMLPostInitializationEvent; -import cpw.mods.fml.common.event.FMLPreInitializationEvent; -import cpw.mods.fml.common.network.NetworkRegistry; -import cpw.mods.fml.common.registry.GameRegistry; -import mantle.utils.CraftingHandler; - -import java.io.File; - -/** - * Mantle - * - * Central mod object for Mantle - * - * @author Sunstrike - */ -@Mod(modid = modId, name = modName, version = modVersion, dependencies = "required-after:Forge@[10.13,)") -public class Mantle -{ - /* Instance of this mod, used for grabbing prototype fields */ - @Instance("Mantle") - public static Mantle instance; - /* Proxies for sides, used for graphics processing */ - @SidedProxy(clientSide = "mantle.client.MProxyClient", serverSide = "mantle.common.MProxyCommon") - - public static MProxyCommon proxy; - public static Manual mantleBook; - /** - * Constructor - * - * EnvChecks invoked here so they run as soon as possible to enhance crash reports that may happen in preinit. - */ - public Mantle() - { - EnvironmentChecks.verifyEnvironmentSanity(); - } - - /** - * FML preinitialisation handler - * - * This is where we load our configs and related data, preparing for main load. - * - * @param evt The FMLPreInitializationEvent from FML - */ - @EventHandler - public void preInit (FMLPreInitializationEvent evt) - { - logger.info("Mantle (" + modVersion + ") -- Preparing for launch."); - logger.info("Entering preinitialization phase."); - CoreConfig.loadConfiguration(evt.getModConfigurationDirectory()); - - NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy); - - mantleBook = (Manual) new Manual().setUnlocalizedName("mantle.manual"); - GameRegistry.registerItem(mantleBook, "mantleBook"); - - } - - /** - * FML initialisation handler - * - * This is where we handle basic loading and populating any missing data in the Repo - * - * @param evt The FMLInitializationEvent from FML - */ - @EventHandler - public void Init (FMLInitializationEvent evt) - { - logger.info("Entering initialization phase."); - proxy.registerRenderer(); - } - - /** - * FML postinitialisation handler - * - * Final chance for cleanup before main game launch - * - * @param evt The FMLPostInitializationEvent from FML - */ - @EventHandler - public void postInit (FMLPostInitializationEvent evt) - { - logger.info("Entering postinitialization phase."); - proxy.readManuals(); - BookData data = new BookData(); - data.unlocalizedName = "item.mantle.manual.test"; - data.toolTip = "Test Book"; - data.modID = CoreRepo.modId; - BookDataStore.addBook(data); - mantleBook.updateManual(); - CoreConfig.loadBookLocations(); - IDDumps.dump(); - } - @EventHandler - public void serverStart(FMLServerStartedEvent evt) - { - CraftingHandler.logConflicts(); - } - -} diff --git a/src/mantle/blocks/BlockUtils.java b/src/mantle/blocks/BlockUtils.java deleted file mode 100644 index e01a9ed..0000000 --- a/src/mantle/blocks/BlockUtils.java +++ /dev/null @@ -1,31 +0,0 @@ -package mantle.blocks; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import cpw.mods.fml.common.registry.GameData; - -public class BlockUtils -{ - public static Block getBlockFromItem (Item item) - { - return Block.getBlockFromItem(item); - } - - @SuppressWarnings("unused") - public static Block getBlockFromItemStack (ItemStack itemStack) - { - return getBlockFromItem(itemStack.getItem()); - } - - public static String getUniqueName (Block block) - { - return GameData.getBlockRegistry().getNameForObject(block); - } - - public static Block getBlockFromUniqueName (String uniqueName) - { - return GameData.getBlockRegistry().getObject(uniqueName); - } - -} diff --git a/src/mantle/blocks/MantleBlock.java b/src/mantle/blocks/MantleBlock.java deleted file mode 100644 index fe43726..0000000 --- a/src/mantle/blocks/MantleBlock.java +++ /dev/null @@ -1,43 +0,0 @@ -package mantle.blocks; - -import mantle.debug.DebugHelper; -import mantle.debug.IDebuggable; -import mantle.items.iface.IDebugItem; -import net.minecraft.block.Block; -import net.minecraft.block.material.Material; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; - -/** - * Root class for inheriting the Minecraft Block. - * - * @author Sunstrike - */ -public abstract class MantleBlock extends Block -{ - - public MantleBlock(Material material) - { - super(material); - } - - // IDebuggable support - Uses a stick for debug purposes. - @Override - public void onBlockClicked (World world, int x, int y, int z, EntityPlayer player) - { - if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && player.getHeldItem() != null - && (player.getHeldItem().getItem() == Items.stick || player.getHeldItem().getItem() instanceof IDebugItem)) - { - TileEntity te = world.getTileEntity(x, y, z); - if (te instanceof IDebuggable) - DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player)); - } - super.onBlockClicked(world, x, y, z, player); - } - -} diff --git a/src/mantle/blocks/abstracts/AdaptiveInventoryLogic.java b/src/mantle/blocks/abstracts/AdaptiveInventoryLogic.java deleted file mode 100644 index 864ad85..0000000 --- a/src/mantle/blocks/abstracts/AdaptiveInventoryLogic.java +++ /dev/null @@ -1,102 +0,0 @@ -package mantle.blocks.abstracts; - -import java.util.Random; - -import mantle.blocks.iface.IFacingLogic; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import cpw.mods.fml.common.FMLCommonHandler; - -public abstract class AdaptiveInventoryLogic extends InventoryLogic implements IFacingLogic -{ - Random random = new Random(); - protected int inventorySize; - - public AdaptiveInventoryLogic() - { - super(0); - } - - protected void adjustInventory (int size, boolean forceAdjust) - { - if (size != inventorySize || forceAdjust) - { - inventorySize = size; - - ItemStack[] tempInv = inventory; - inventory = new ItemStack[size]; - int invLength = tempInv.length > inventory.length ? inventory.length : tempInv.length; - System.arraycopy(tempInv, 0, inventory, 0, invLength); - - if (tempInv.length > inventory.length) - { - for (int i = inventory.length; i < tempInv.length; i++) - { - ItemStack stack = tempInv[i]; - if (stack != null) - { - float jumpX = random.nextFloat() * 0.8F + 0.1F; - float jumpY = random.nextFloat() * 0.8F + 0.1F; - float jumpZ = random.nextFloat() * 0.8F + 0.1F; - - int offsetX = 0; - int offsetY = 0; - int offsetZ = 0; - switch (getTossDirection()) - { - case 0: // -y - offsetY--; - break; - case 1: // +y - offsetY++; - break; - case 2: // +z - offsetZ--; - break; - case 3: // -z - offsetZ++; - break; - case 4: // +x - offsetX--; - break; - case 5: // -x - offsetX++; - break; - } - - while (stack.stackSize > 0) - { - int itemSize = random.nextInt(21) + 10; - - if (itemSize > stack.stackSize) - { - itemSize = stack.stackSize; - } - - stack.stackSize -= itemSize; - EntityItem entityitem = new EntityItem(worldObj, (double) ((float) xCoord + jumpX + offsetX), (double) ((float) yCoord + jumpY), - (double) ((float) zCoord + jumpZ + offsetZ), new ItemStack(stack.getItem(), itemSize, stack.getMetadata())); - - if (stack.hasTagCompound()) - { - entityitem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy()); - } - - float offset = 0.05F; - entityitem.motionX = (double) ((float) random.nextGaussian() * offset); - entityitem.motionY = (double) ((float) random.nextGaussian() * offset + 0.2F); - entityitem.motionZ = (double) ((float) random.nextGaussian() * offset); - worldObj.spawnEntityInWorld(entityitem); - } - } - } - } - } - } - - public int getTossDirection () - { - return getRenderDirection(); - } -} \ No newline at end of file diff --git a/src/mantle/blocks/abstracts/ExpandableInventoryLogic.java b/src/mantle/blocks/abstracts/ExpandableInventoryLogic.java deleted file mode 100644 index de97a44..0000000 --- a/src/mantle/blocks/abstracts/ExpandableInventoryLogic.java +++ /dev/null @@ -1,217 +0,0 @@ -package mantle.blocks.abstracts; - -import java.util.*; -import net.minecraft.entity.player.*; -import net.minecraft.inventory.*; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.*; -import net.minecraft.world.World; - -public abstract class ExpandableInventoryLogic extends InventoryLogic implements IInventory -{ - - public ExpandableInventoryLogic() - { - super(0); - } - - protected ArrayList inventory = new ArrayList(); - protected String invName; - - @Override - public ItemStack getStackInSlot (int slot) - { - return slot < inventory.size() ? inventory.get(slot) : null; - } - - public boolean isStackInSlot (int slot) - { - return slot < inventory.size() && inventory.get(slot) != null; - } - - @Override - public int getSizeInventory () - { - return inventory.size(); - } - - public int getMaxSize () - { - return 64; - } - - @Override - public int getInventoryStackLimit () - { - return 64; - } - - public boolean canDropInventorySlot (int slot) - { - return true; - } - - @Override - public void setInventorySlotContents (int slot, ItemStack itemstack) - { - if (slot < inventory.size()) - { - inventory.set(slot, itemstack); - } - else if (slot == inventory.size()) - { - inventory.add(itemstack); - } - else if (slot < getMaxSize()) - { - inventory.ensureCapacity(slot); - inventory.set(slot, itemstack); - } - else - { - return; - } - if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) - { - itemstack.stackSize = getInventoryStackLimit(); - } - } - - @Override - public ItemStack decrStackSize (int slot, int quantity) - { - if (slot < inventory.size() && inventory.get(slot) != null) - { - if (inventory.get(slot).stackSize <= quantity) - { - ItemStack stack = inventory.get(slot); - inventory.set(slot, null); - return stack; - } - ItemStack split = inventory.get(slot).splitStack(quantity); - if (inventory.get(slot).stackSize == 0) - { - inventory.set(slot, null); - } - return split; - } - else - { - return null; - } - } - - /* Supporting methods */ - @Override - public boolean isUseableByPlayer (EntityPlayer entityplayer) - { - if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this) - return false; - - else - return entityplayer.getDistance((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D; - - } - - public abstract Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z); - - /* NBT */ - @Override - public void readFromNBT (NBTTagCompound tags) - { - super.readFromNBT(tags); - this.invName = tags.getString("InvName"); - NBTTagList nbttaglist = tags.getTagList("Items", 9); - inventory = new ArrayList(); - inventory.ensureCapacity(nbttaglist.tagCount() > getMaxSize() ? getMaxSize() : nbttaglist.tagCount()); - for (int iter = 0; iter < nbttaglist.tagCount(); iter++) - { - NBTTagCompound tagList = nbttaglist.getCompoundTagAt(iter); - byte slotID = tagList.getByte("Slot"); - if (slotID >= 0 && slotID < inventory.size()) - { - inventory.set(slotID, ItemStack.loadItemStackFromNBT(tagList)); - } - } - } - - @Override - public void writeToNBT (NBTTagCompound tags) - { - super.writeToNBT(tags); - if (invName != null) - tags.setString("InvName", invName); - NBTTagList nbttaglist = new NBTTagList(); - for (int iter = 0; iter < inventory.size(); iter++) - { - if (inventory.get(iter) != null) - { - NBTTagCompound tagList = new NBTTagCompound(); - tagList.setByte("Slot", (byte) iter); - inventory.get(iter).writeToNBT(tagList); - nbttaglist.appendTag(tagList); - } - } - - tags.setTag("Items", nbttaglist); - } - - /* Default implementations of hardly used methods */ - public ItemStack getStackInSlotOnClosing (int slot) - { - return null; - } - - public void openChest () - { - } - - public void closeChest () - { - } - - protected abstract String getDefaultName (); - - public void setInvName (String name) - { - this.invName = name; - } - - public String getInvName () - { - return this.isInvNameLocalized() ? this.invName : getDefaultName(); - } - - public boolean isInvNameLocalized () - { - return this.invName != null && this.invName.length() > 0; - } - - public void cleanInventory () - { - Iterator i1 = inventory.iterator(); - while (i1.hasNext()) - { - if (i1.next() == null) - { - i1.remove(); - } - } - } - - @Override - public boolean isItemValidForSlot (int slot, ItemStack itemstack) - { - if (slot < getSizeInventory()) - { - if (inventory.get(slot) == null || itemstack.stackSize + inventory.get(slot).stackSize <= getInventoryStackLimit()) - return true; - } - else - { - return slot < getMaxSize(); - } - return false; - } - -} \ No newline at end of file diff --git a/src/mantle/blocks/abstracts/InventoryBlock.java b/src/mantle/blocks/abstracts/InventoryBlock.java deleted file mode 100644 index 08067dd..0000000 --- a/src/mantle/blocks/abstracts/InventoryBlock.java +++ /dev/null @@ -1,217 +0,0 @@ -package mantle.blocks.abstracts; - -import java.util.Random; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; -import mantle.blocks.iface.IActiveLogic; -import mantle.blocks.iface.IFacingLogic; -import mantle.debug.DebugHelper; -import mantle.debug.IDebuggable; -import net.minecraft.block.Block; -import net.minecraft.block.BlockContainer; -import net.minecraft.block.material.Material; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.tileentity.TileEntityChest; -import net.minecraft.util.IIcon; -import net.minecraft.util.MathHelper; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -public abstract class InventoryBlock extends BlockContainer -{ - protected Random rand = new Random(); - - protected InventoryBlock(Material material) - { - super(material); - } - - /* Logic backend */ - public TileEntity createNewTileEntity (World var1) - { - return null; - } - - public abstract TileEntity createNewTileEntity (World world, int metadata); - - public abstract Integer getGui (World world, int x, int y, int z, EntityPlayer entityplayer); - - public abstract Object getModInstance (); - - @Override - public boolean onBlockActivated (World world, int x, int y, int z, EntityPlayer player, int side, float clickX, float clickY, float clickZ) - { - if (player.isSneaking()) - return false; - - Integer integer = getGui(world, x, y, z, player); - if (integer == null || integer == -1) - { - return false; - } - else - { - if (!world.isRemote) - player.openGui(getModInstance(), integer, world, x, y, z); - return true; - } - } - - /* Inventory */ - @Override - public void breakBlock (World par1World, int x, int y, int z, Block blockID, int meta) - { - TileEntity te = par1World.getTileEntity(x, y, z); - - if (te != null && te instanceof InventoryLogic) - { - InventoryLogic logic = (InventoryLogic) te; - logic.removeBlock(); - for (int iter = 0; iter < logic.getSizeInventory(); ++iter) - { - ItemStack stack = logic.getStackInSlot(iter); - - if (stack != null && logic.canDropInventorySlot(iter)) - { - float jumpX = rand.nextFloat() * 0.8F + 0.1F; - float jumpY = rand.nextFloat() * 0.8F + 0.1F; - float jumpZ = rand.nextFloat() * 0.8F + 0.1F; - - while (stack.stackSize > 0) - { - int itemSize = rand.nextInt(21) + 10; - - if (itemSize > stack.stackSize) - { - itemSize = stack.stackSize; - } - - stack.stackSize -= itemSize; - EntityItem entityitem = new EntityItem(par1World, (double) ((float) x + jumpX), (double) ((float) y + jumpY), (double) ((float) z + jumpZ), new ItemStack(stack.getItem(), - itemSize, stack.getMetadata())); - - if (stack.hasTagCompound()) - { - entityitem.getEntityItem().setTagCompound((NBTTagCompound) stack.getTagCompound().copy()); - } - - float offset = 0.05F; - entityitem.motionX = (double) ((float) rand.nextGaussian() * offset); - entityitem.motionY = (double) ((float) rand.nextGaussian() * offset + 0.2F); - entityitem.motionZ = (double) ((float) rand.nextGaussian() * offset); - par1World.spawnEntityInWorld(entityitem); - } - } - } - } - - super.breakBlock(par1World, x, y, z, blockID, meta); - } - - /* Placement */ - - int side = -1; - - //This class does not have an actual block placed in the world - @Override - public int onBlockPlaced (World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int meta) - { - this.side = side; - return meta; - } - - @Override - @SuppressWarnings("deprecation") // TODO: Remove this when setDirection calls updated. - public void onBlockPlacedBy (World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack stack) - { - TileEntity logic = world.getTileEntity(x, y, z); - if (logic instanceof IFacingLogic) - { - IFacingLogic direction = (IFacingLogic) logic; - // TODO: Convert all setDirection calls to modern invokation, when that's ready. - if (side != -1) - { - direction.setDirection(side); - side = -1; - } - if (entityliving == null) - { - direction.setDirection(0F, 0F, null); - } - else - { - direction.setDirection(entityliving.rotationYaw * 4F, entityliving.rotationPitch, entityliving); - } - } - - if (logic instanceof InventoryLogic) - { - InventoryLogic inv = (InventoryLogic) logic; - inv.placeBlock(entityliving, stack); - if (stack.hasDisplayName()) - { - inv.setInvName(stack.getDisplayName()); - } - } - } - - @SuppressWarnings("unused") - public static boolean isActive (IBlockAccess world, int x, int y, int z) - { - TileEntity logic = world.getTileEntity(x, y, z); - if (logic instanceof IActiveLogic) - { - return ((IActiveLogic) logic).getActive(); - } - return false; - } - - public int damageDropped (int meta) - { - return meta; - } - - /* Textures */ - public IIcon[] icons; - - public abstract String[] getTextureNames (); - - public abstract String getTextureDomain (int textureNameIndex); - - @Override - public void registerIcons (IIconRegister iconRegister) - { - String[] textureNames = getTextureNames(); - this.icons = new IIcon[textureNames.length]; - - for (int i = 0; i < this.icons.length; ++i) - { - this.icons[i] = iconRegister.registerIcon(getTextureDomain(i) + ":" + textureNames[i]); - } - } - - /* IDebuggable */ - @Override - public void onBlockClicked (World world, int x, int y, int z, EntityPlayer player) - { - if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER && player.getHeldItem() != null && player.getHeldItem().getItem() != null && player.getHeldItem().getItem() == Items.stick) - { - TileEntity te = world.getTileEntity(x, y, z); - if (te instanceof IDebuggable) - { - DebugHelper.handleDebugData(((IDebuggable) te).getDebugInfo(player)); - } - } - - super.onBlockClicked(world, x, y, z, player); - } -} \ No newline at end of file diff --git a/src/mantle/blocks/abstracts/InventoryLogic.java b/src/mantle/blocks/abstracts/InventoryLogic.java deleted file mode 100644 index f7620b4..0000000 --- a/src/mantle/blocks/abstracts/InventoryLogic.java +++ /dev/null @@ -1,286 +0,0 @@ -package mantle.blocks.abstracts; - -import mantle.debug.DebugData; -import mantle.debug.IDebuggable; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; - -/* - * A simple logic class for storing items - * Abstract to avoid instantiation - */ - -public abstract class InventoryLogic extends TileEntity implements IInventory, IDebuggable -{ - protected ItemStack[] inventory; - protected String invName; - protected int stackSizeLimit; - - public InventoryLogic(int invSize) - { - this(invSize, 64); - } - - public InventoryLogic(int invSize, int maxStackSize) - { - inventory = new ItemStack[invSize]; - stackSizeLimit = maxStackSize; - } - - /* Inventory management */ - - @Override - public ItemStack getStackInSlot (int slot) - { - return slot < inventory.length ? inventory[slot] : null; - } - - public boolean isStackInSlot (int slot) - { - return slot < inventory.length && inventory[slot] != null; - } - - @Override - public int getSizeInventory () - { - return inventory.length; - } - - @Override - public int getInventoryStackLimit () - { - return stackSizeLimit; - } - - public boolean canDropInventorySlot (int slot) - { - return true; - } - - @Override - public void setInventorySlotContents (int slot, ItemStack itemstack) - { - inventory[slot] = itemstack; - if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) - { - itemstack.stackSize = getInventoryStackLimit(); - } - } - - @Override - public ItemStack decrStackSize (int slot, int quantity) - { - if (inventory[slot] != null) - { - if (inventory[slot].stackSize <= quantity) - { - ItemStack stack = inventory[slot]; - inventory[slot] = null; - return stack; - } - ItemStack split = inventory[slot].splitStack(quantity); - if (inventory[slot].stackSize == 0) - { - inventory[slot] = null; - } - return split; - } - else - { - return null; - } - } - - /* Supporting methods */ - @Override - public boolean isUseableByPlayer (EntityPlayer entityplayer) - { - if (worldObj.getTileEntity(xCoord, yCoord, zCoord) != this) - return false; - - else - return entityplayer.getDistance((double) xCoord + 0.5D, (double) yCoord + 0.5D, (double) zCoord + 0.5D) <= 64D; - - } - - public abstract Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z); - - /* NBT */ - @Override - public void readFromNBT (NBTTagCompound tags) - { - super.readFromNBT(tags); - readInventoryFromNBT(tags); - } - - public void readInventoryFromNBT (NBTTagCompound tags) - { - super.readFromNBT(tags); - NBTTagList nbttaglist = tags.getTagList("Items", 10); - this.inventory = new ItemStack[this.getSizeInventory()]; - - if (tags.hasKey("CustomName", 8)) - { - this.invName = tags.getString("CustomName"); - } - - for (int i = 0; i < nbttaglist.tagCount(); ++i) - { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - int j = nbttagcompound1.getByte("Slot") & 255; - - if (j >= 0 && j < this.inventory.length) - { - this.inventory[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1); - } - } - - //Not removed in case of things going terribly wrong -// super.readFromNBT(tags); -// this.invName = tags.getString("InvName"); -// NBTTagList nbttaglist = tags.getTagList("Items", 9); -// inventory = new ItemStack[getSizeInventory()]; -// for (int iter = 0; iter < nbttaglist.tagCount(); iter++) -// { -// NBTTagCompound tagList = (NBTTagCompound) nbttaglist.getCompoundTagAt(iter); -// byte slotID = tagList.getByte("Slot"); -// if (slotID >= 0 && slotID < inventory.length) -// { -// inventory[slotID] = ItemStack.loadItemStackFromNBT(tagList); -// } -// } - } - - @Override - public void writeToNBT (NBTTagCompound tags) - { - super.writeToNBT(tags); - writeInventoryToNBT(tags); - } - - public void writeInventoryToNBT (NBTTagCompound tags) - { - super.writeToNBT(tags); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.inventory.length; ++i) - { - if (this.inventory[i] != null) - { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte)i); - this.inventory[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - - tags.setTag("Items", nbttaglist); - - if (this.isInvNameLocalized()) - { - tags.setString("CustomName", this.invName); - } - - //Not removed in case of things going terribly wrong -// if (invName != null) -// tags.setString("InvName", invName); -// NBTTagList nbttaglist = new NBTTagList(); -// for (int iter = 0; iter < inventory.length; iter++) -// { -// if (inventory[iter] != null) -// { -// NBTTagCompound tagList = new NBTTagCompound(); -// tagList.setByte("Slot", (byte) iter); -// inventory[iter].writeToNBT(tagList); -// nbttaglist.appendTag(tagList); -// } -// } -// -// tags.setTag("Items", nbttaglist); - } - - /* Cause of the heisenbug. Do not uncomment! */ - /*public void superReadFromNBT (NBTTagCompound tags) - { - super.readFromNBT(tags); - } - - public void superWriteToNBT (NBTTagCompound tags) - { - super.writeToNBT(tags); - }*/ - - /* Default implementations of hardly used methods */ - public ItemStack getStackInSlotOnClosing (int slot) - { - return null; - } - - public void openChest () - { - } - - public void closeChest () - { - } - - protected abstract String getDefaultName (); - - public void setInvName (String name) - { - this.invName = name; - } - - public String getInvName () - { - return this.isInvNameLocalized() ? this.invName : getDefaultName(); - } - - public boolean hasCustomInventoryName() - { - return isInvNameLocalized(); - } - - public boolean isInvNameLocalized () - { - return this.invName != null && this.invName.length() > 0; - } - - @Override - public boolean isItemValidForSlot (int slot, ItemStack itemstack) - { - if (slot < getSizeInventory()) - { - if (inventory[slot] == null || itemstack.stackSize + inventory[slot].stackSize <= getInventoryStackLimit()) - return true; - } - return false; - } - - public void placeBlock (EntityLivingBase entity, ItemStack stack) - { - - } - - public void removeBlock () - { - - } - - /* IDebuggable */ - @Override - public DebugData getDebugInfo (EntityPlayer player) - { - String[] strs = new String[1]; - strs[0] = "invName: " + invName + ", inventory.length: " + inventory.length + ", stackSizeLimit: " + stackSizeLimit; - return new DebugData(player, getClass(), strs); - } -} \ No newline at end of file diff --git a/src/mantle/blocks/abstracts/InventorySlab.java b/src/mantle/blocks/abstracts/InventorySlab.java deleted file mode 100644 index 449b00e..0000000 --- a/src/mantle/blocks/abstracts/InventorySlab.java +++ /dev/null @@ -1,90 +0,0 @@ -package mantle.blocks.abstracts; - -import java.util.List; - -import net.minecraft.block.material.Material; -import net.minecraft.entity.Entity; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -/** - * Slab version of InventoryBlock. - * - * @author mDiyo - */ -public abstract class InventorySlab extends InventoryBlock -{ - public InventorySlab(Material material) - { - super(material); - } - - /* Rendering */ - @Override - //TODO: renderAsNormalBlock() - public boolean renderAsNormalBlock () - { - return false; - } - - //TODO: isOpaqueCube() - @Override - public boolean isOpaqueCube () - { - return false; - } - - //TODO shouldSideBeRendered - @Override - public boolean shouldSideBeRendered (IBlockAccess world, int x, int y, int z, int side) - { - if (side > 1) - return super.shouldSideBeRendered(world, x, y, z, side); - - int meta = world.getBlockMetadata(x, y, z); - boolean top = (meta | 8) == 1; - if ((top && side == 0) || (!top && side == 1)) - return true; - - return super.shouldSideBeRendered(world, x, y, z, side); - } - - //TODO: addCollisionBoxesToList() - @Override - @SuppressWarnings("rawtypes") - public void addCollisionBoxesToList (World world, int x, int y, int z, AxisAlignedBB axisalignedbb, List arraylist, Entity entity) - { - setBlockBoundsBasedOnState(world, x, y, z); - super.addCollisionBoxesToList(world, x, y, z, axisalignedbb, arraylist, entity); - } - - public void setBlockBoundsForItemRender () - { - //TODO: setBlockBounds - setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); - } - - public void setBlockBoundsBasedOnState (IBlockAccess world, int x, int y, int z) - { - int meta = world.getBlockMetadata(x, y, z) / 8; - float minY = meta == 1 ? 0.5F : 0.0F; - float maxY = meta == 1 ? 1.0F : 0.5F; - setBlockBounds(0.0F, minY, 0F, 1.0F, maxY, 1.0F); - } - - public int onBlockPlaced (World par1World, int blockX, int blockY, int blockZ, int side, float clickX, float clickY, float clickZ, int metadata) - { - if (side == 1) - return metadata; - if (side == 0 || clickY >= 0.5F) - return metadata | 8; - - return metadata; - } - - public int damageDropped (int meta) - { - return meta % 8; - } -} \ No newline at end of file diff --git a/src/mantle/blocks/abstracts/MultiItemBlock.java b/src/mantle/blocks/abstracts/MultiItemBlock.java deleted file mode 100644 index 5ebcfce..0000000 --- a/src/mantle/blocks/abstracts/MultiItemBlock.java +++ /dev/null @@ -1,71 +0,0 @@ -package mantle.blocks.abstracts; - -import static mantle.lib.CoreRepo.logger; -import net.minecraft.block.Block; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.util.MathHelper; - -/** - * - * @author progwml6 - * base class for itemBlocks with different unlocalized names based on metadata - */ - -public class MultiItemBlock extends ItemBlock -{ - private String blockType[]; - private String unlocalizedName; - private String append; - private int specialIndex[] = { -1, -1 }; - - public MultiItemBlock(Block b, String itemBlockUnlocalizedName, String[] blockTypes) - { - super(b); - if (itemBlockUnlocalizedName.isEmpty()) - this.unlocalizedName = super.getUnlocalizedName(); - else - this.unlocalizedName = itemBlockUnlocalizedName; - this.blockType = blockTypes; - this.append = ""; - } - - public MultiItemBlock(Block b, String itemBlockUnlocalizedName, String appendToEnd, String[] blockTypes) - { - super(b); - this.unlocalizedName = itemBlockUnlocalizedName; - this.blockType = blockTypes; - this.append = "." + appendToEnd; - } - - public void setSpecialIndex (int clampIndex, int stringBuilderIndex) - { - specialIndex[0] = clampIndex; - specialIndex[1] = stringBuilderIndex; - } - - public int getMetadata (int meta) - { - return meta; - } - - public String getUnlocalizedName (ItemStack itemstack) - { - - int pos = MathHelper.clamp_int(itemstack.getMetadata(), 0, (specialIndex[0] > -1) ? specialIndex[0] : (blockType.length - 1)); - int sbIndex = (specialIndex[1] > -1) ? pos : (specialIndex[1] - pos); - if (sbIndex < 0) - sbIndex = -1 * sbIndex; - try - { - return (new StringBuilder()).append(unlocalizedName).append(".").append(blockType[sbIndex - 1]).append(append).toString(); - } - catch (ArrayIndexOutOfBoundsException ex) - { - logger.warn("[MultiItemBlock] Caught array index error in getUnlocalizedName: " + ex.getMessage()); - logger.warn("[MultiItemBlock] Returning unlocalized name: " + getUnlocalizedName()); - return getUnlocalizedName(); - } - } - -} diff --git a/src/mantle/blocks/abstracts/MultiServantLogic.java b/src/mantle/blocks/abstracts/MultiServantLogic.java deleted file mode 100644 index 146f108..0000000 --- a/src/mantle/blocks/abstracts/MultiServantLogic.java +++ /dev/null @@ -1,212 +0,0 @@ -package mantle.blocks.abstracts; - -import mantle.blocks.BlockUtils; -import mantle.blocks.iface.IMasterLogic; -import mantle.blocks.iface.IServantLogic; -import mantle.debug.DebugData; -import mantle.debug.IDebuggable; -import mantle.world.CoordTuple; -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import cpw.mods.fml.common.registry.GameRegistry; - -public class MultiServantLogic extends TileEntity implements IServantLogic, IDebuggable -{ - boolean hasMaster; - CoordTuple master; - Block masterBlock; - byte masterMeat; //Typo, it stays! - - public boolean canUpdate () - { - return false; - } - - public boolean getHasMaster () - { - return hasMaster; - } - - public boolean hasValidMaster () - { - if (!hasMaster) - return false; - - if (worldObj.getBlock(master.x, master.y, master.z) == masterBlock && worldObj.getBlockMetadata(master.x, master.y, master.z) == masterMeat) - return true; - - else - { - hasMaster = false; - master = null; - return false; - } - } - - public CoordTuple getMasterPosition () - { - return master; - } - - public void overrideMaster (int x, int y, int z) - { - hasMaster = true; - master = new CoordTuple(x, y, z); - masterBlock = worldObj.getBlock(x, y, z); - masterMeat = (byte) worldObj.getBlockMetadata(x, y, z); - } - - public void removeMaster () - { - hasMaster = false; - master = null; - masterBlock = null; - masterMeat = 0; - } - - @Override - public boolean setPotentialMaster (IMasterLogic master, World w, int x, int y, int z) - { - return !hasMaster; - } - - @Deprecated - public boolean verifyMaster (IMasterLogic logic, int x, int y, int z) - { - if (master.equalCoords(x, y, z) && worldObj.getBlock(x, y, z) == masterBlock && worldObj.getBlockMetadata(x, y, z) == masterMeat) - return true; - else - return false; - } - - @Override - public boolean verifyMaster (IMasterLogic logic, World world, int x, int y, int z) - { - if (hasMaster) - { - return hasValidMaster(); - } - else - { - overrideMaster(x, y, z); - return true; - } - } - - @Override - public void invalidateMaster (IMasterLogic master, World w, int x, int y, int z) - { - hasMaster = false; - master = null; - } - - public void notifyMasterOfChange () - { - if (hasValidMaster()) - { - IMasterLogic logic = (IMasterLogic) worldObj.getTileEntity(master.x, master.y, master.z); - logic.notifyChange(this, xCoord, yCoord, zCoord); - } - } - - public void readCustomNBT (NBTTagCompound tags) - { - hasMaster = tags.getBoolean("TiedToMaster"); - if (hasMaster) - { - int xCenter = tags.getInteger("xCenter"); - int yCenter = tags.getInteger("yCenter"); - int zCenter = tags.getInteger("zCenter"); - master = new CoordTuple(xCenter, yCenter, zCenter); - masterBlock = BlockUtils.getBlockFromUniqueName(tags.getString("MasterBlockName")); - masterMeat = tags.getByte("masterMeat"); - } - } - - public void writeCustomNBT (NBTTagCompound tags) - { - tags.setBoolean("TiedToMaster", hasMaster); - if (hasMaster) - { - tags.setInteger("xCenter", master.x); - tags.setInteger("yCenter", master.y); - tags.setInteger("zCenter", master.z); - tags.setString("MasterBlockName", BlockUtils.getUniqueName(masterBlock)); - tags.setByte("masterMeat", masterMeat); - } - } - - @Override - public void readFromNBT (NBTTagCompound tags) - { - super.readFromNBT(tags); - readCustomNBT(tags); - } - - @Override - public void writeToNBT (NBTTagCompound tags) - { - super.writeToNBT(tags); - writeCustomNBT(tags); - } - - /* Packets */ - @Override - public Packet getDescriptionPacket () - { - NBTTagCompound tag = new NBTTagCompound(); - writeCustomNBT(tag); - return new S35PacketUpdateTileEntity(xCoord, yCoord, zCoord, 1, tag); - } - - @Override - public void onDataPacket (NetworkManager net, S35PacketUpdateTileEntity packet) - { - readCustomNBT(packet.getNbtCompound()); - worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord); - worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); - } - - /* IDebuggable */ - @Override - public DebugData getDebugInfo (EntityPlayer player) - { - String[] strs = new String[2]; - strs[0] = "Location: x" + xCoord + ", y" + yCoord + ", z" + zCoord; - if (hasMaster) - { - strs[1] = "masterBlock: " + masterBlock.toString() + ", masterMeat: " + masterMeat; - } - else - { - strs[1] = "No active master."; - } - return new DebugData(player, getClass(), strs); - } - - public World getWorld () - { - return super.getWorld(); - } - - @Deprecated - public boolean setMaster (int x, int y, int z) - { - if (!hasMaster || worldObj.getBlock(master.x, master.y, master.z) != masterBlock || (worldObj.getBlockMetadata(master.x, master.y, master.z) != masterMeat)) - { - overrideMaster(x, y, z); - return true; - } - else - { - return false; - } - } - -} diff --git a/src/mantle/blocks/iface/IActiveLogic.java b/src/mantle/blocks/iface/IActiveLogic.java deleted file mode 100644 index c670f8d..0000000 --- a/src/mantle/blocks/iface/IActiveLogic.java +++ /dev/null @@ -1,13 +0,0 @@ -package mantle.blocks.iface; - -/** - * Marks blocks that can be active and inactive. - * - * @author mDiyo - */ -public interface IActiveLogic -{ - public boolean getActive (); - - public void setActive (boolean flag); -} diff --git a/src/mantle/blocks/iface/IFacingLogic.java b/src/mantle/blocks/iface/IFacingLogic.java deleted file mode 100644 index a7d4b03..0000000 --- a/src/mantle/blocks/iface/IFacingLogic.java +++ /dev/null @@ -1,27 +0,0 @@ -package mantle.blocks.iface; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraftforge.common.util.ForgeDirection; - -/** - * Logic for blocks which have a specific direction facing. - * - * @author mDiyo - */ -public interface IFacingLogic -{ - - public byte getRenderDirection (); - - public ForgeDirection getForgeDirection (); - - @Deprecated - public void setDirection (int side); - - @Deprecated - public void setDirection (float yaw, float pitch, EntityLivingBase player); - - /** This will be added next version - * public void setDirection(int side, float yaw, float pitch, EntityLivingBase player); */ - -} diff --git a/src/mantle/blocks/iface/IMasterLogic.java b/src/mantle/blocks/iface/IMasterLogic.java deleted file mode 100644 index 8788ed3..0000000 --- a/src/mantle/blocks/iface/IMasterLogic.java +++ /dev/null @@ -1,12 +0,0 @@ -package mantle.blocks.iface; - -public interface IMasterLogic -{ - /** Called when servants change their state - * - * @param x Servant X - * @param y Servant Y - * @param z Servant Z - */ - public void notifyChange (IServantLogic servant, int x, int y, int z); -} diff --git a/src/mantle/blocks/iface/IMasterNode.java b/src/mantle/blocks/iface/IMasterNode.java deleted file mode 100644 index 1906f92..0000000 --- a/src/mantle/blocks/iface/IMasterNode.java +++ /dev/null @@ -1,8 +0,0 @@ -package mantle.blocks.iface; - -public interface IMasterNode extends IMasterLogic, IServantLogic -{ - public boolean isCurrentlyMaster (); - - public boolean isEquivalentMaster (IMasterLogic master); -} diff --git a/src/mantle/blocks/iface/IServantLogic.java b/src/mantle/blocks/iface/IServantLogic.java deleted file mode 100644 index 3794d20..0000000 --- a/src/mantle/blocks/iface/IServantLogic.java +++ /dev/null @@ -1,47 +0,0 @@ -package mantle.blocks.iface; - -import mantle.world.CoordTuple; -import net.minecraft.world.World; - -public interface IServantLogic -{ - public CoordTuple getMasterPosition (); - - /** The block should already have a valid master */ - public void notifyMasterOfChange (); - - /** Checks if this block can be tied to this master - * - * @param master - * @param world the world of master - * @param x xCoord of master - * @param y yCoord of master - * @param z zCoord of master - * @return whether the servant can be tied to this master - */ - - public boolean setPotentialMaster (IMasterLogic master, World world, int xMaster, int yMaster, int zMaster); - - /** Used to set and verify that this is the block's master - * - * @param master - * @param world - * @param x xCoord of master - * @param y yCoord of master - * @param z zCoord of master - * @return Is this block tied to this master? - */ - - public boolean verifyMaster (IMasterLogic master, World world, int xMaster, int yMaster, int zMaster); - - /** Exactly what it says on the tin - * - * @param master - * @param world - * @param x xCoord of master - * @param y yCoord of master - * @param z zCoord of master - */ - - public void invalidateMaster (IMasterLogic master, World world, int xMaster, int yMaster, int zMaster); -} diff --git a/src/mantle/books/BookData.java b/src/mantle/books/BookData.java deleted file mode 100644 index 61752cf..0000000 --- a/src/mantle/books/BookData.java +++ /dev/null @@ -1,32 +0,0 @@ -package mantle.books; - -import mantle.client.SmallFontRenderer; -import net.minecraft.util.ResourceLocation; - -import org.w3c.dom.Document; - -public class BookData -{ - public String unlocalizedName = new String(); - public String toolTip = new String(); - public String modID = new String(); - public ResourceLocation leftImage = new ResourceLocation("mantle", "textures/gui/bookleft.png"); - public ResourceLocation rightImage = new ResourceLocation("mantle", "textures/gui/bookright.png"); - public ResourceLocation itemImage = new ResourceLocation("mantle", "textures/items/mantlebook_blue.png"); - public Document doc = ManualReader.readManual("/assets/mantle/manuals/test.xml"); - //font can be left null if so, the default from mantle will be used - public SmallFontRenderer font; - public Boolean isTranslatable = false; - public boolean isFromZip = false; - - public Document getDoc () - { - return this.doc; - } - - public String getFullUnlocalizedName () - { - return this.modID + ":" + this.unlocalizedName; - } - -} diff --git a/src/mantle/books/BookDataStore.java b/src/mantle/books/BookDataStore.java deleted file mode 100644 index de7f13f..0000000 --- a/src/mantle/books/BookDataStore.java +++ /dev/null @@ -1,51 +0,0 @@ -package mantle.books; - -import java.util.List; - -import com.google.common.collect.HashBiMap; -import com.google.common.collect.Lists; - -public class BookDataStore -{ - private static HashBiMap data = HashBiMap.create(); - private static HashBiMap intMap = HashBiMap.create(); - private static List zipBooks= Lists.newArrayList(); - public static void addBook (BookData bd) - { - int insertOrder = data.size(); - data.put(bd.getFullUnlocalizedName(), bd); - intMap.put(insertOrder, bd.getFullUnlocalizedName()); - if(bd.isFromZip) - zipBooks.add(bd.getFullUnlocalizedName()); - - } - - public static BookData getBookfromName (String ModID, String unlocalizedName) - { - return getBookFromName(ModID + ":" + unlocalizedName); - } - - public static BookData getBookFromName (String fullBookName) - { - return data.get(fullBookName); - } - - public static BookData getBookfromID (int bookIDNum) - { - return data.get(intMap.get(bookIDNum)); - } - - public static int getIDFromName (String FullUnlocalizedName) - { - return intMap.inverse().get(FullUnlocalizedName); - } - - public static int getIDFromBook (BookData b) - { - return getIDFromName(data.inverse().get(b)); - } - - public static List getZipBooks(){ - return zipBooks; - } -} diff --git a/src/mantle/books/ManualReader.java b/src/mantle/books/ManualReader.java deleted file mode 100644 index 5e9a204..0000000 --- a/src/mantle/books/ManualReader.java +++ /dev/null @@ -1,50 +0,0 @@ -package mantle.books; - -import static mantle.lib.CoreRepo.logger; - -import java.io.InputStream; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import mantle.Mantle; - -import org.w3c.dom.Document; - -public class ManualReader -{ - public static Document readManual (String location) - { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - - try - { - logger.info("Loading Manual XML from: " + location); - InputStream stream = Mantle.class.getResourceAsStream(location); - return readManual(stream, location); - } - catch (Exception e) - { - e.printStackTrace(); - return null; - } - } - public static Document readManual (InputStream is, String filenameOrLocation) - { - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - - try - { - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(is); - doc.getDocumentElement().normalize(); - return doc; - } - catch (Exception e) - { - logger.error("Failed to Load Manual XML from: " + filenameOrLocation); - e.printStackTrace(); - return null; - } - } -} diff --git a/src/mantle/books/client/BookImage.java b/src/mantle/books/client/BookImage.java deleted file mode 100644 index 8482568..0000000 --- a/src/mantle/books/client/BookImage.java +++ /dev/null @@ -1,17 +0,0 @@ -package mantle.books.client; - -import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.util.ResourceLocation; - -public class BookImage { - public int height, width; - public DynamicTexture texture; - public ResourceLocation resource; - - public BookImage(int width, int height, DynamicTexture texture, ResourceLocation resource) { - this.width = width; - this.height = height; - this.texture = texture; - this.resource = resource; - } -} diff --git a/src/mantle/books/external/BookIS.java b/src/mantle/books/external/BookIS.java deleted file mode 100644 index f0ecd76..0000000 --- a/src/mantle/books/external/BookIS.java +++ /dev/null @@ -1,22 +0,0 @@ -package mantle.books.external; - -public class BookIS -{ - //users chosen nickname for this specific itemstack - public String cname; - - //fully qualified name from the game registry for the item/block in question - public String fullISName; - - public int metadata; - - public String tags; - - public int stackSize; - - public int getStackSize () - { - return stackSize >= 0 ? stackSize : 1; - } - -} diff --git a/src/mantle/books/external/BookLoad.java b/src/mantle/books/external/BookLoad.java deleted file mode 100644 index 1c0bc0c..0000000 --- a/src/mantle/books/external/BookLoad.java +++ /dev/null @@ -1,20 +0,0 @@ -package mantle.books.external; - -import com.google.gson.JsonObject; - -public class BookLoad -{ -public String unlocalizedName; -public String tooltip; -public boolean translatable; -public String BookIcon; -public String LeftImage; -public String rightImage; -public BookIS[] registerItemStacks; -public JsonObject[] smallRecipes; -public JsonObject[] largeRecipes; -public JsonObject[] furnaceRecipes; -public JsonObject[] manualIcons; - - -} diff --git a/src/mantle/books/external/ZipLoader.java b/src/mantle/books/external/ZipLoader.java deleted file mode 100644 index c54a263..0000000 --- a/src/mantle/books/external/ZipLoader.java +++ /dev/null @@ -1,259 +0,0 @@ -package mantle.books.external; - -import java.awt.image.BufferedImage; -import java.io.File; -import java.util.Enumeration; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import javax.imageio.ImageIO; - -import static mantle.lib.CoreRepo.logger; -import mantle.books.BookData; -import mantle.books.BookDataStore; -import mantle.books.ManualReader; -import mantle.books.client.BookImage; -import mantle.lib.client.MantleClientRegistry; -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.texture.DynamicTexture; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.JsonToNBT; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ResourceLocation; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; - -import com.google.common.base.Charsets; -import com.google.common.collect.Maps; -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.relauncher.Side; - -public class ZipLoader -{ - public static Map loadedIS = Maps.newHashMap(); - - public static BookData loadZip (File f) - { - BookLoad bl; - String flName = new String(); - String flExt = new String(); - String lImg = new String(); - String rImg = new String(); - String bIcon = new String(); - String unlocName = new String(); - String toolTip = new String(); - Boolean translatable = false; - BookData b = new BookData(); - boolean isClient = FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT; - if (f.exists()) - { - if (FilenameUtils.getExtension(f.getPath()).equalsIgnoreCase("zip")) - { - try - { - logger.info("Loading book zip " + f.getName()); - ZipFile zipfile = new ZipFile(f); - Enumeration e = zipfile.entries(); - while (e.hasMoreElements()) - { - ZipEntry entry = e.nextElement(); - flName = entry.getName(); - flExt = FilenameUtils.getExtension(flName); - if (!entry.isDirectory()) - { - if (isClient && isImage(flExt)) - { - String id = FilenameUtils.getBaseName(flName); - BufferedImage img = ImageIO.read(zipfile.getInputStream(entry)); - DynamicTexture dynTexture = new DynamicTexture(img); - ResourceLocation rsLoc = Minecraft.getMinecraft().getTextureManager().getDynamicTextureLocation(id, dynTexture); - BookImage bI = new BookImage(img.getWidth(), img.getHeight(), dynTexture, rsLoc); - MantleClientRegistry.imageCache.put(id, bI); - } - if (flExt.equalsIgnoreCase("xml")) - { - b.doc = ManualReader.readManual(zipfile.getInputStream(entry), flName); - } - if (flExt.equalsIgnoreCase("lang")) - { - //TODO 1.7 put this data into the vanilla lang stuffs - } - if (flExt.equalsIgnoreCase("json")) - { - Gson g = new Gson(); - bl = g.fromJson(IOUtils.toString(zipfile.getInputStream(entry), Charsets.UTF_8), BookLoad.class); - for (BookIS bis : bl.registerItemStacks) - { - try - { - ItemStack is = loadedIS.get(bis.cname); - if (is == null) - { - Block blok = (Block) Block.blockRegistry.getObject(bis.cname); - Item it = (Item) Item.itemRegistry.getObject(bis.cname); - if (it != null) - { - is = new ItemStack(it, bis.getStackSize(), bis.metadata); - } - - else if (bl != null) - { - is = new ItemStack(blok, bis.getStackSize(), bis.metadata); - } - if (is != null) - { - if (bis.tags != null && !bis.tags.isEmpty()) - { - try - { - is.stackTagCompound = (NBTTagCompound) JsonToNBT.func_150315_a(bis.tags); - } - catch (Exception e1) - { - } - } - loadedIS.put(bis.cname, is); - } - } - } - catch (Exception e1) - { - } - } - if (isClient) - { - for (JsonObject jso : bl.smallRecipes) - { - if (jso != null) - { - ItemStack out = loadedIS.get(jso.get("out").getAsString()); - ItemStack in[] = getISArray(jso.getAsJsonArray("in")); - String name = jso.get("name").getAsString(); - if (out != null && in != null && in.length <= 4 && name != null && !name.isEmpty()) - { - MantleClientRegistry.registerManualSmallRecipe(name, out, in); - } - } - } - for (JsonObject jso : bl.largeRecipes) - { - if (jso != null) - { - ItemStack out = loadedIS.get(jso.get("out").getAsString()); - ItemStack in[] = getISArray(jso.getAsJsonArray("in")); - String name = jso.get("name").getAsString(); - if (out != null && in != null && in.length <= 9 && name != null && !name.isEmpty()) - { - MantleClientRegistry.registerManualLargeRecipe(name, out, in); - } - } - } - for (JsonObject jso : bl.furnaceRecipes) - { - if (jso != null) - { - ItemStack out = loadedIS.get(jso.get("out").getAsString()); - ItemStack in = loadedIS.get(jso.get("in").getAsString()); - String name = jso.get("name").getAsString(); - if (out != null && in != null && name != null && !name.isEmpty()) - { - MantleClientRegistry.registerManualFurnaceRecipe(name, out, in); - } - } - } - for (JsonObject jso : bl.manualIcons) - { - if (jso != null) - { - ItemStack in = loadedIS.get(jso.get("stack").getAsString()); - String name = jso.get("name").getAsString(); - if (in != null && name != null && !name.isEmpty()) - { - MantleClientRegistry.registerManualIcon(name, in); - } - } - } - } - b.unlocalizedName = bl.unlocalizedName; - b.toolTip = bl.tooltip; - b.isTranslatable = bl.translatable; - b.leftImage = bl.LeftImage == null ? new ResourceLocation("mantle", "textures/gui/bookleft.png") : MantleClientRegistry.getBookImageFromCache(bl.LeftImage).resource; - b.rightImage = bl.rightImage == null ? new ResourceLocation("mantle", "textures/gui/bookright.png") - : MantleClientRegistry.getBookImageFromCache(bl.rightImage).resource; - b.itemImage = bl.BookIcon == null ? new ResourceLocation("mantle", "textures/items/mantlebook_blue.png") - : MantleClientRegistry.getBookImageFromCache(bl.BookIcon).resource; - b.isFromZip = true; - BookDataStore.addBook(b); - } - } - - } - zipfile.close(); - b.unlocalizedName = unlocName; - b.toolTip = toolTip; - b.isTranslatable = translatable; - b.leftImage = lImg == null ? new ResourceLocation("mantle", "textures/gui/bookleft.png") : MantleClientRegistry.getBookImageFromCache(lImg).resource; - b.rightImage = rImg == null ? new ResourceLocation("mantle", "textures/gui/bookright.png") : MantleClientRegistry.getBookImageFromCache(rImg).resource; - b.itemImage = bIcon == null ? new ResourceLocation("mantle", "textures/items/mantlebook_blue.png") : MantleClientRegistry.getBookImageFromCache(bIcon).resource; - b.isFromZip = true; - BookDataStore.addBook(b); - } - catch (Exception e) - { - logger.info(" Error Loading book zip " + f.getName()); - } - return null; - - } - else - { - logger.error("Attempted to load non-zip file for mantle book. File " + f.getName() + " will be skipped"); - } - } - else - { - logger.error("Attempted to load non-existant file for mantle book. File will be skipped"); - - } - return null; - } - - public static boolean isImage (String ext) - { - if (ext.equalsIgnoreCase("png")) - return true; - return false; - } - - public static ItemStack[] getISArray (JsonArray a) - { - ItemStack[] is = new ItemStack[a.size()]; - ItemStack loadedStack; - for (int i = 0; i < a.size(); i++) - { - if (a.get(i).getAsString() != null && !a.get(i).getAsString().isEmpty() && a.get(i).getAsString().equals("none")) - { - is[i] = null; - } - else - { - loadedStack = loadedIS.get(a.get(i).getAsString()); - if (loadedStack == null) - { - is = null; - return is; - } - is[i] = loadedStack; - } - } - return is; - } -} diff --git a/src/mantle/client/MProxyClient.java b/src/mantle/client/MProxyClient.java deleted file mode 100644 index 922c385..0000000 --- a/src/mantle/client/MProxyClient.java +++ /dev/null @@ -1,101 +0,0 @@ -package mantle.client; - -import static mantle.lib.CoreRepo.logger; - -import java.util.HashMap; -import java.util.Map; - -import mantle.books.BookData; -import mantle.books.BookDataStore; -import mantle.client.gui.GuiManual; -import mantle.client.pages.BlankPage; -import mantle.client.pages.BookPage; -import mantle.client.pages.ContentsTablePage; -import mantle.client.pages.CraftingPage; -import mantle.client.pages.FurnacePage; -import mantle.client.pages.PicturePage; -import mantle.client.pages.SectionPage; -import mantle.client.pages.SidebarPage; -import mantle.client.pages.TextPage; -import mantle.client.pages.TitlePage; -import mantle.common.MProxyCommon; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraft.world.World; - -public class MProxyClient extends MProxyCommon -{ - - public static final String MINECRAFT_ASCII_PATH = "minecraft:textures/font/ascii.png"; - - public static SmallFontRenderer smallFontRenderer; - - /* Registers any rendering code. */ - public void registerRenderer () - { - Minecraft mc = Minecraft.getMinecraft(); - if (mc.getTextureManager() == null) - logger.error("Vanilla texture manager is null!"); - if (mc.renderEngine == null) - logger.error("Vanilla render engine is null!"); - smallFontRenderer = new SmallFontRenderer(mc.gameSettings, new ResourceLocation(MINECRAFT_ASCII_PATH), mc.renderEngine, false); - } - - public static Map> pageClasses = new HashMap>(); - - public static void registerManualPage (String type, Class clazz) - { - pageClasses.put(type, clazz); - } - - public static Class getPageClass (String type) - { - return pageClasses.get(type); - } - - public void readManuals () - { - initManualPages(); - } - - void initManualPages () - { - MProxyClient.registerManualPage("crafting", CraftingPage.class); - MProxyClient.registerManualPage("picture", PicturePage.class); - MProxyClient.registerManualPage("text", TextPage.class); - MProxyClient.registerManualPage("intro", TextPage.class); - MProxyClient.registerManualPage("sectionpage", SectionPage.class); - MProxyClient.registerManualPage("intro", TitlePage.class); - MProxyClient.registerManualPage("contents", ContentsTablePage.class); - MProxyClient.registerManualPage("furnace", FurnacePage.class); - MProxyClient.registerManualPage("sidebar", SidebarPage.class); - MProxyClient.registerManualPage("blank", BlankPage.class); - } - - @Override - public Object getClientGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z) - { - if (ID == manualGuiID) - { - ItemStack stack = player.getCurrentEquippedItem(); - if (stack == null) - logger.error("Null stack in book."); - if (stack != null && stack.getItem() == null) - logger.error("Null item in book."); - if (stack != null && stack.getItem() != null && stack.getItem().getUnlocalizedName() == null) - logger.error("Null unlocalized name in book."); - else - { - return new GuiManual(stack, MProxyClient.getBookDataFromStack(stack)); - } - } - return null; - } - - private static BookData getBookDataFromStack (ItemStack stack) - { - return BookDataStore.getBookFromName(stack.getItem().getUnlocalizedName(stack)); - } -} diff --git a/src/mantle/client/RenderItemCopy.java b/src/mantle/client/RenderItemCopy.java deleted file mode 100644 index ac49c2a..0000000 --- a/src/mantle/client/RenderItemCopy.java +++ /dev/null @@ -1,679 +0,0 @@ -package mantle.client; - -import java.util.Random; - -import net.minecraft.block.Block; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.ItemRenderer; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.entity.Render; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.entity.Entity; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.init.Items; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.util.MathHelper; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.client.ForgeHooksClient; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class RenderItemCopy extends Render -{ - private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png"); - private RenderBlocks itemRenderBlocks = new RenderBlocks(); - - /** The RNG used in RenderItem (for bobbing itemstacks on the ground) */ - private Random random = new Random(); - public boolean renderWithColor = true; - - /** Defines the zLevel of rendering of item on GUI. */ - public float zLevel; - public static boolean renderInFrame; - - public RenderItemCopy() - { - this.shadowSize = 0.15F; - this.shadowOpaque = 0.75F; - } - - /** - * Renders the item - */ - public void doRenderItem (EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9) - { - this.bindEntityTexture(par1EntityItem); - this.random.setSeed(187L); - ItemStack itemstack = par1EntityItem.getEntityItem(); - - if (itemstack.getItem() != null) - { - GL11.glPushMatrix(); - float f2 = shouldBob() ? MathHelper.sin(((float) par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F : 0F; - float f3 = (((float) par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float) Math.PI); - byte b0 = getMiniBlockCount(itemstack); - - GL11.glTranslatef((float) par2, (float) par4 + f2, (float) par6); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - float f4; - float f5; - float f6; - int i; - - Block block = null; - - block = Block.getBlockFromItem(itemstack.getItem()); - - if (ForgeHooksClient.renderEntityItem(par1EntityItem, itemstack, f2, f3, random, renderManager.renderEngine, new RenderBlocks(), 000)) // TODO what goes here not 000 - { - ; - } - else if (itemstack.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d(block.getRenderType())) - { - GL11.glRotatef(f3, 0.0F, 1.0F, 0.0F); - - if (renderInFrame) - { - GL11.glScalef(1.25F, 1.25F, 1.25F); - GL11.glTranslatef(0.0F, 0.05F, 0.0F); - GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); - } - - float f7 = 0.25F; - int j = block.getRenderType(); - - if (j == 1 || j == 19 || j == 12 || j == 2) - { - f7 = 0.5F; - } - - GL11.glScalef(f7, f7, f7); - - for (i = 0; i < b0; ++i) - { - GL11.glPushMatrix(); - - if (i > 0) - { - f5 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f7; - f4 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f7; - f6 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / f7; - GL11.glTranslatef(f5, f4, f6); - } - - f5 = 1.0F; - //TODO renderBlockAsItem - this.itemRenderBlocks.renderBlockAsItem(block, itemstack.getMetadata(), f5); - GL11.glPopMatrix(); - } - } - else - { - float f8; - - if (itemstack.getItemSpriteNumber() == 1 && itemstack.getItem().requiresMultipleRenderPasses()) - { - if (renderInFrame) - { - GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); - GL11.glTranslatef(0.0F, -0.05F, 0.0F); - } - else - { - GL11.glScalef(0.5F, 0.5F, 0.5F); - } - - for (int k = 0; k < itemstack.getItem().getRenderPasses(itemstack.getCurrentDurability()); ++k) - { - this.random.setSeed(187L); - IIcon icon = itemstack.getItem().getIcon(itemstack, k); - f8 = 1.0F; - - if (this.renderWithColor) - { - i = itemstack.getItem().getColorFromItemStack(itemstack, k); - f5 = (float) (i >> 16 & 255) / 255.0F; - f4 = (float) (i >> 8 & 255) / 255.0F; - f6 = (float) (i & 255) / 255.0F; - GL11.glColor4f(f5 * f8, f4 * f8, f6 * f8, 1.0F); - this.renderDroppedItem(par1EntityItem, icon, b0, par9, f5 * f8, f4 * f8, f6 * f8, k); - } - else - { - this.renderDroppedItem(par1EntityItem, icon, b0, par9, 1.0F, 1.0F, 1.0F, k); - } - } - } - else - { - if (renderInFrame) - { - GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); - GL11.glTranslatef(0.0F, -0.05F, 0.0F); - } - else - { - GL11.glScalef(0.5F, 0.5F, 0.5F); - } - - IIcon icon1 = itemstack.getIconIndex(); - - if (this.renderWithColor) - { - int l = itemstack.getItem().getColorFromItemStack(itemstack, 0); - f8 = (float) (l >> 16 & 255) / 255.0F; - float f9 = (float) (l >> 8 & 255) / 255.0F; - f5 = (float) (l & 255) / 255.0F; - f4 = 1.0F; - this.renderDroppedItem(par1EntityItem, icon1, b0, par9, f8 * f4, f9 * f4, f5 * f4); - } - else - { - this.renderDroppedItem(par1EntityItem, icon1, b0, par9, 1.0F, 1.0F, 1.0F); - } - } - } - - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - GL11.glPopMatrix(); - } - } - - protected ResourceLocation func_110796_a (EntityItem par1EntityItem) - { - return this.renderManager.renderEngine.getResourceLocation(par1EntityItem.getEntityItem().getItemSpriteNumber()); - } - - /** - * Renders a dropped item - */ - private void renderDroppedItem (EntityItem par1EntityItem, IIcon par2Icon, int par3, float par4, float par5, float par6, float par7) - { - renderDroppedItem(par1EntityItem, par2Icon, par3, par4, par5, par6, par7, 0); - } - - private void renderDroppedItem (EntityItem par1EntityItem, IIcon par2Icon, int par3, float par4, float par5, float par6, float par7, int pass) - { - Tessellator tessellator = Tessellator.instance; - - if (par2Icon == null) - { - TextureManager texturemanager = Minecraft.getMinecraft().getTextureManager(); - ResourceLocation resourcelocation = texturemanager.getResourceLocation(par1EntityItem.getEntityItem().getItemSpriteNumber()); - par2Icon = ((TextureMap) texturemanager.getTexture(resourcelocation)).getAtlasSprite("missingno"); - } - - float f4 = par2Icon.getMinU(); - float f5 = par2Icon.getMaxU(); - float f6 = par2Icon.getMinV(); - float f7 = par2Icon.getMaxV(); - float f8 = 1.0F; - float f9 = 0.5F; - float f10 = 0.25F; - float f11; - - if (this.renderManager.options.fancyGraphics) - { - GL11.glPushMatrix(); - - if (renderInFrame) - { - GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F); - } - else - { - GL11.glRotatef((((float) par1EntityItem.age + par4) / 20.0F + par1EntityItem.hoverStart) * (180F / (float) Math.PI), 0.0F, 1.0F, 0.0F); - } - - float f12 = 0.0625F; - f11 = 0.021875F; - ItemStack itemstack = par1EntityItem.getEntityItem(); - int j = itemstack.stackSize; - byte b0 = getMiniItemCount(itemstack); - - GL11.glTranslatef(-f9, -f10, -((f12 + f11) * (float) b0 / 2.0F)); - - for (int k = 0; k < b0; ++k) - { - // Makes items offset when in 3D, like when in 2D, looks much better. Considered a vanilla bug... - if (k > 0 && shouldSpreadItems()) - { - float x = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; - float y = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; - float z = (random.nextFloat() * 2.0F - 1.0F) * 0.3F / 0.5F; - GL11.glTranslatef(x, y, f12 + f11); - } - else - { - GL11.glTranslatef(0f, 0f, f12 + f11); - } - - if (itemstack.getItemSpriteNumber() == 0) - { - this.bindTexture(TextureMap.locationBlocksTexture); - } - else - { - this.bindTexture(TextureMap.locationItemsTexture); - } - - GL11.glColor4f(par5, par6, par7, 1.0F); - ItemRenderer.renderItemIn2D(tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12); - - if (itemstack.hasEffect(pass)) - { - GL11.glDepthFunc(GL11.GL_EQUAL); - GL11.glDisable(GL11.GL_LIGHTING); - this.renderManager.renderEngine.bindTexture(RES_ITEM_GLINT); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); - float f13 = 0.76F; - GL11.glColor4f(0.5F * f13, 0.25F * f13, 0.8F * f13, 1.0F); - GL11.glMatrixMode(GL11.GL_TEXTURE); - GL11.glPushMatrix(); - float f14 = 0.125F; - GL11.glScalef(f14, f14, f14); - float f15 = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F * 8.0F; - GL11.glTranslatef(f15, 0.0F, 0.0F); - GL11.glRotatef(-50.0F, 0.0F, 0.0F, 1.0F); - ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, f12); - GL11.glPopMatrix(); - GL11.glPushMatrix(); - GL11.glScalef(f14, f14, f14); - f15 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F * 8.0F; - GL11.glTranslatef(-f15, 0.0F, 0.0F); - GL11.glRotatef(10.0F, 0.0F, 0.0F, 1.0F); - ItemRenderer.renderItemIn2D(tessellator, 0.0F, 0.0F, 1.0F, 1.0F, 255, 255, f12); - GL11.glPopMatrix(); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDepthFunc(GL11.GL_LEQUAL); - } - } - - GL11.glPopMatrix(); - } - else - { - for (int l = 0; l < par3; ++l) - { - GL11.glPushMatrix(); - - if (l > 0) - { - f11 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F; - float f16 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F; - float f17 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F; - GL11.glTranslatef(f11, f16, f17); - } - - if (!renderInFrame) - { - GL11.glRotatef(180.0F - this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F); - } - - GL11.glColor4f(par5, par6, par7, 1.0F); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - tessellator.addVertexWithUV((double) (0.0F - f9), (double) (0.0F - f10), 0.0D, (double) f4, (double) f7); - tessellator.addVertexWithUV((double) (f8 - f9), (double) (0.0F - f10), 0.0D, (double) f5, (double) f7); - tessellator.addVertexWithUV((double) (f8 - f9), (double) (1.0F - f10), 0.0D, (double) f5, (double) f6); - tessellator.addVertexWithUV((double) (0.0F - f9), (double) (1.0F - f10), 0.0D, (double) f4, (double) f6); - tessellator.draw(); - GL11.glPopMatrix(); - } - } - } - - /** - * Renders the item's icon or block into the UI at the specified position. - */ - public void renderItemIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5) - { - renderItemIntoGUI(par1FontRenderer, par2TextureManager, par3ItemStack, par4, par5, false); - } - - public void renderItemIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5, boolean renderEffect) - { - Item k = par3ItemStack.getItem(); - int l; - if(k == null) - { - k = Items.iron_pickaxe; - l = 0; - } - else - { - l = par3ItemStack.getCurrentDurability(); - } - Object object = par3ItemStack.getItem() == null ? null : par3ItemStack.getIconIndex(); - float f; - int i1; - float f1; - float f2; - - Block block = Block.getBlockFromItem(k); - //TODO renderItemIn3d - if (block != null && par3ItemStack.getItemSpriteNumber() == 0 && RenderBlocks.renderItemIn3d(block.getRenderType())) - { - par2TextureManager.bindTexture(TextureMap.locationBlocksTexture); - GL11.glPushMatrix(); - GL11.glTranslatef((float) (par4 - 2), (float) (par5 + 3), -3.0F + this.zLevel); - GL11.glScalef(10.0F, 10.0F, 10.0F); - GL11.glTranslatef(1.0F, 0.5F, 1.0F); - GL11.glScalef(1.0F, 1.0F, -1.0F); - GL11.glRotatef(210.0F, 1.0F, 0.0F, 0.0F); - GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F); - i1 = par3ItemStack.getItem().getColorFromItemStack(par3ItemStack, 0); - f = (float) (i1 >> 16 & 255) / 255.0F; - f1 = (float) (i1 >> 8 & 255) / 255.0F; - f2 = (float) (i1 & 255) / 255.0F; - - if (this.renderWithColor) - { - GL11.glColor4f(f, f1, f2, 1.0F); - } - - GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); - //TODO FIX THESE - //this.itemRenderBlocks.useInventoryTint = this.renderWithColor; - this.itemRenderBlocks.renderBlockAsItem(block, l, 1.0F); - //TODO FIX THESE - //this.itemRenderBlocks.useInventoryTint = true; - GL11.glPopMatrix(); - } - else if (k != null && k.requiresMultipleRenderPasses()) - { - GL11.glDisable(GL11.GL_LIGHTING); - - for (int j1 = 0; j1 < k.getRenderPasses(l); ++j1) - { - par2TextureManager.bindTexture(par3ItemStack.getItemSpriteNumber() == 0 ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture); - IIcon icon = k.getIcon(par3ItemStack, j1); - int k1 = k.getColorFromItemStack(par3ItemStack, j1); - f1 = (float) (k1 >> 16 & 255) / 255.0F; - f2 = (float) (k1 >> 8 & 255) / 255.0F; - float f3 = (float) (k1 & 255) / 255.0F; - - if (this.renderWithColor) - { - GL11.glColor4f(f1, f2, f3, 1.0F); - } - - this.renderIcon(par4, par5, icon, 16, 16); - - if (par3ItemStack.hasEffect(j1)) - { - renderEffect(par2TextureManager, par4, par5); - } - } - - GL11.glEnable(GL11.GL_LIGHTING); - } - else - { - GL11.glDisable(GL11.GL_LIGHTING); - ResourceLocation resourcelocation = par2TextureManager.getResourceLocation(par3ItemStack.getItemSpriteNumber()); - par2TextureManager.bindTexture(resourcelocation); - - if (object == null) - { - object = ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture(resourcelocation)).getAtlasSprite("missingno"); - } - - i1 = k.getColorFromItemStack(par3ItemStack, 0); - f = (float) (i1 >> 16 & 255) / 255.0F; - f1 = (float) (i1 >> 8 & 255) / 255.0F; - f2 = (float) (i1 & 255) / 255.0F; - - if (this.renderWithColor) - { - GL11.glColor4f(f, f1, f2, 1.0F); - } - - this.renderIcon(par4, par5, (IIcon) object, 16, 16); - GL11.glEnable(GL11.GL_LIGHTING); - - if (par3ItemStack.hasEffect(0)) - { - renderEffect(par2TextureManager, par4, par5); - } - } - - GL11.glEnable(GL11.GL_CULL_FACE); - } - - private void renderEffect (TextureManager manager, int x, int y) - { - GL11.glDepthFunc(GL11.GL_GREATER); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDepthMask(false); - manager.bindTexture(RES_ITEM_GLINT); - this.zLevel -= 50.0F; - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_DST_COLOR); - GL11.glColor4f(0.5F, 0.25F, 0.8F, 1.0F); - this.renderGlint(x * 431278612 + y * 32178161, x - 2, y - 2, 20, 20); - GL11.glDisable(GL11.GL_BLEND); - GL11.glDepthMask(true); - this.zLevel += 50.0F; - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDepthFunc(GL11.GL_LEQUAL); - } - - /** - * Render the item's icon or block into the GUI, including the glint effect. - */ - public void renderItemAndEffectIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5) - { - if (par3ItemStack != null) - { - if (!ForgeHooksClient.renderInventoryItem(new RenderBlocks(), par2TextureManager, par3ItemStack, renderWithColor, zLevel, (float) par4, (float) par5)) - { - this.renderItemIntoGUI(par1FontRenderer, par2TextureManager, par3ItemStack, par4, par5, true); - } - - /* Modders must handle this themselves if they use custom renderers! - if (par3ItemStack.hasEffect()) - { - GL11.glDepthFunc(GL11.GL_GREATER); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDepthMask(false); - par2TextureManager.bindTexture(RES_ITEM_GLINT); - this.zLevel -= 50.0F; - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_DST_COLOR); - GL11.glColor4f(0.5F, 0.25F, 0.8F, 1.0F); - this.renderGlint(par4 * 431278612 + par5 * 32178161, par4 - 2, par5 - 2, 20, 20); - GL11.glDisable(GL11.GL_BLEND); - GL11.glDepthMask(true); - this.zLevel += 50.0F; - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDepthFunc(GL11.GL_LEQUAL); - } - */ - } - } - - private void renderGlint (int par1, int par2, int par3, int par4, int par5) - { - for (int j1 = 0; j1 < 2; ++j1) - { - if (j1 == 0) - { - GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); - } - - if (j1 == 1) - { - GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); - } - - float f = 0.00390625F; - float f1 = 0.00390625F; - float f2 = (float) (Minecraft.getSystemTime() % (long) (3000 + j1 * 1873)) / (3000.0F + (float) (j1 * 1873)) * 256.0F; - float f3 = 0.0F; - Tessellator tessellator = Tessellator.instance; - float f4 = 4.0F; - - if (j1 == 1) - { - f4 = -1.0F; - } - - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double) (par2 + 0), (double) (par3 + par5), (double) this.zLevel, (double) ((f2 + (float) par5 * f4) * f), (double) ((f3 + (float) par5) * f1)); - tessellator.addVertexWithUV((double) (par2 + par4), (double) (par3 + par5), (double) this.zLevel, (double) ((f2 + (float) par4 + (float) par5 * f4) * f), - (double) ((f3 + (float) par5) * f1)); - tessellator.addVertexWithUV((double) (par2 + par4), (double) (par3 + 0), (double) this.zLevel, (double) ((f2 + (float) par4) * f), (double) ((f3 + 0.0F) * f1)); - tessellator.addVertexWithUV((double) (par2 + 0), (double) (par3 + 0), (double) this.zLevel, (double) ((f2 + 0.0F) * f), (double) ((f3 + 0.0F) * f1)); - tessellator.draw(); - } - } - - /** - * Renders the item's overlay information. Examples being stack count or damage on top of the item's image at the - * specified position. - */ - public void renderItemOverlayIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5) - { - this.renderItemOverlayIntoGUI(par1FontRenderer, par2TextureManager, par3ItemStack, par4, par5, (String) null); - } - - public void renderItemOverlayIntoGUI (SmallFontRenderer par1FontRenderer, TextureManager par2TextureManager, ItemStack par3ItemStack, int par4, int par5, String par6Str) - { - if (par3ItemStack != null) - { - if (par3ItemStack.stackSize > 1 || par6Str != null) - { - String s1 = par6Str == null ? String.valueOf(par3ItemStack.stackSize) : par6Str; - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - par1FontRenderer.drawStringWithShadow(s1, par4 + 19 - 2 - par1FontRenderer.getStringWidth(s1), par5 + 6 + 3, 16777215); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - } - - if (par3ItemStack.isItemDamaged()) - { - int k = (int) Math.round(13.0D - (double) par3ItemStack.getCurrentDurability() * 13.0D / (double) par3ItemStack.getMaxDurability()); - int l = (int) Math.round(255.0D - (double) par3ItemStack.getCurrentDurability() * 255.0D / (double) par3ItemStack.getMaxDurability()); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glDisable(GL11.GL_TEXTURE_2D); - Tessellator tessellator = Tessellator.instance; - int i1 = 255 - l << 16 | l << 8; - int j1 = (255 - l) / 4 << 16 | 16128; - this.renderQuad(tessellator, par4 + 2, par5 + 13, 13, 2, 0); - this.renderQuad(tessellator, par4 + 2, par5 + 13, 12, 1, j1); - this.renderQuad(tessellator, par4 + 2, par5 + 13, k, 1, i1); - GL11.glEnable(GL11.GL_TEXTURE_2D); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - } - } - } - - /** - * Adds a quad to the tesselator at the specified position with the set width and height and color. Args: - * tessellator, x, y, width, height, color - */ - private void renderQuad (Tessellator par1Tessellator, int par2, int par3, int par4, int par5, int par6) - { - par1Tessellator.startDrawingQuads(); - par1Tessellator.setColorOpaque_I(par6); - par1Tessellator.addVertex((double) (par2 + 0), (double) (par3 + 0), 0.0D); - par1Tessellator.addVertex((double) (par2 + 0), (double) (par3 + par5), 0.0D); - par1Tessellator.addVertex((double) (par2 + par4), (double) (par3 + par5), 0.0D); - par1Tessellator.addVertex((double) (par2 + par4), (double) (par3 + 0), 0.0D); - par1Tessellator.draw(); - } - - public void renderIcon (int par1, int par2, IIcon par3Icon, int par4, int par5) - { - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + par5), (double) this.zLevel, (double) par3Icon.getMinU(), (double) par3Icon.getMaxV()); - tessellator.addVertexWithUV((double) (par1 + par4), (double) (par2 + par5), (double) this.zLevel, (double) par3Icon.getMaxU(), (double) par3Icon.getMaxV()); - tessellator.addVertexWithUV((double) (par1 + par4), (double) (par2 + 0), (double) this.zLevel, (double) par3Icon.getMaxU(), (double) par3Icon.getMinV()); - tessellator.addVertexWithUV((double) (par1 + 0), (double) (par2 + 0), (double) this.zLevel, (double) par3Icon.getMinU(), (double) par3Icon.getMinV()); - tessellator.draw(); - } - - protected ResourceLocation getEntityTexture (Entity par1Entity) - { - return this.func_110796_a((EntityItem) par1Entity); - } - - /** - * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic - * (Render 1) - ret = 2; - if (stack.stackSize > 5) - ret = 3; - if (stack.stackSize > 20) - ret = 4; - if (stack.stackSize > 40) - ret = 5; - return ret; - } - - /** - * Allows for a subclass to override how many rendered items appear in a - * "mini item 3d stack" - * @param stack - * @return - */ - public byte getMiniItemCount (ItemStack stack) - { - byte ret = 1; - if (stack.stackSize > 1) - ret = 2; - if (stack.stackSize > 15) - ret = 3; - if (stack.stackSize > 31) - ret = 4; - return ret; - } -} diff --git a/src/mantle/client/SmallFontRenderer.java b/src/mantle/client/SmallFontRenderer.java deleted file mode 100644 index 3d0e030..0000000 --- a/src/mantle/client/SmallFontRenderer.java +++ /dev/null @@ -1,1067 +0,0 @@ -package mantle.client; - -import static mantle.lib.CoreRepo.logger; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; -import java.text.Bidi; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Random; - -import javax.imageio.ImageIO; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.texture.TextureManager; -import net.minecraft.client.resources.IResourceManager; -import net.minecraft.client.resources.IResourceManagerReloadListener; -import net.minecraft.client.settings.GameSettings; -import net.minecraft.util.ChatAllowedCharacters; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class SmallFontRenderer implements IResourceManagerReloadListener -{ - private static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256]; - - /** Array of width of all the characters in default.png */ - private int[] charWidth = new int[256]; - - /** the height in pixels of default text */ - public int FONT_HEIGHT = 9; - public Random fontRandom = new Random(); - - /** - * Array of the start/end column (in upper/lower nibble) for every glyph in the /font directory. - */ - private byte[] glyphWidth = new byte[65536]; - - /** - * Array of RGB triplets defining the 16 standard chat colors followed by 16 darker version of the same colors for - * drop shadows. - */ - private int[] colorCode = new int[32]; - private final ResourceLocation locationFontTexture; - - /** The RenderEngine used to load and setup glyph textures. */ - private TextureManager renderEngine; - - /** Current X coordinate at which to draw the next character. */ - private float posX; - - /** Current Y coordinate at which to draw the next character. */ - private float posY; - - /** - * If true, strings should be rendered with Unicode fonts instead of the default.png font - */ - private boolean unicodeFlag; - - /** - * If true, the Unicode Bidirectional Algorithm should be run before rendering any string. - */ - private boolean bidiFlag; - - /** Used to specify new red value for the current color. */ - private float red; - - /** Used to specify new blue value for the current color. */ - private float blue; - - /** Used to specify new green value for the current color. */ - private float green; - - /** Used to speify new alpha value for the current color. */ - private float alpha; - - /** Text color of the currently rendering string. */ - private int textColor; - - /** Set if the "k" style (random) is active in currently rendering string */ - private boolean randomStyle; - - /** Set if the "l" style (bold) is active in currently rendering string */ - private boolean boldStyle; - - /** Set if the "o" style (italic) is active in currently rendering string */ - private boolean italicStyle; - - /** - * Set if the "n" style (underlined) is active in currently rendering string - */ - private boolean underlineStyle; - - /** - * Set if the "m" style (strikethrough) is active in currently rendering string - */ - private boolean strikethroughStyle; - - public SmallFontRenderer(GameSettings par1GameSettings, ResourceLocation par2ResourceLocation, TextureManager par3TextureManager, boolean par4) - { - this.locationFontTexture = par2ResourceLocation; - //logger.error(this.locationFontTexture.toString() + " " + this.locationFontTexture.getResourcePath()); - this.renderEngine = par3TextureManager; - this.unicodeFlag = true; - if (this.renderEngine != null) - this.renderEngine.bindTexture(par2ResourceLocation); - if (this.renderEngine == null) - logger.error("renderEngine is null"); - //Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation("Minecraft", "textures/font/ascii.png")); - for (int i = 0; i < 32; ++i) - { - int j = (i >> 3 & 1) * 85; - int k = (i >> 2 & 1) * 170 + j; - int l = (i >> 1 & 1) * 170 + j; - int i1 = (i >> 0 & 1) * 170 + j; - - if (i == 6) - { - k += 85; - } - - if (par1GameSettings.anaglyph) - { - int j1 = (k * 30 + l * 59 + i1 * 11) / 100; - int k1 = (k * 30 + l * 70) / 100; - int l1 = (k * 30 + i1 * 70) / 100; - k = j1; - l = k1; - i1 = l1; - } - - if (i >= 16) - { - k /= 4; - l /= 4; - i1 /= 4; - } - - this.colorCode[i] = (k & 255) << 16 | (l & 255) << 8 | i1 & 255; - } - - this.readGlyphSizes(); - } - - public void onResourceManagerReload (IResourceManager par1ResourceManager) - { - this.readFontTexture(); - } - - private void readFontTexture () - { - BufferedImage bufferedimage; - - try - { - bufferedimage = ImageIO.read(Minecraft.getMinecraft().getResourceManager().getResource(this.locationFontTexture).getInputStream()); - } - catch (IOException ioexception) - { - throw new RuntimeException(ioexception); - } - - int i = bufferedimage.getWidth(); - int j = bufferedimage.getHeight(); - int[] aint = new int[i * j]; - bufferedimage.getRGB(0, 0, i, j, aint, 0, i); - int k = j / 16; - int l = i / 16; - byte b0 = 1; - float f = 8.0F / (float) l; - int i1 = 0; - - while (i1 < 256) - { - int j1 = i1 % 16; - int k1 = i1 / 16; - - if (i1 == 32) - { - this.charWidth[i1] = 3 + b0; - } - - int l1 = l - 1; - - while (true) - { - if (l1 >= 0) - { - int i2 = j1 * l + l1; - boolean flag = true; - - for (int j2 = 0; j2 < k && flag; ++j2) - { - int k2 = (k1 * l + j2) * i; - - if ((aint[i2 + k2] >> 24 & 255) != 0) - { - flag = false; - } - } - - if (flag) - { - --l1; - continue; - } - } - - ++l1; - this.charWidth[i1] = (int) (0.5D + (double) ((float) l1 * f)) + b0; - ++i1; - break; - } - } - } - - private void readGlyphSizes () - { - try - { - InputStream inputstream = Minecraft.getMinecraft().getResourceManager().getResource(new ResourceLocation("font/glyph_sizes.bin")).getInputStream(); - inputstream.read(this.glyphWidth); - } - catch (IOException ioexception) - { - throw new RuntimeException(ioexception); - } - } - - /** - * Pick how to render a single character and return the width used. - */ - private float renderCharAtPos (int par1, char par2, boolean par3) - { - return par2 == 32 ? 4.0F : (par1 > 0 && !this.unicodeFlag ? this.renderDefaultChar(par1 + 32, par3) : this.renderUnicodeChar(par2, par3)); - } - - /** - * Render a single character with the default.png font at current (posX,posY) location... - */ - private float renderDefaultChar (int par1, boolean par2) - { - float f = (float) (par1 % 16 * 8); - float f1 = (float) (par1 / 16 * 8); - float f2 = par2 ? 1.0F : 0.0F; - this.renderEngine.bindTexture(this.locationFontTexture); - float f3 = (float) this.charWidth[par1] - 0.01F; - GL11.glBegin(GL11.GL_TRIANGLE_STRIP); - GL11.glTexCoord2f(f / 128.0F, f1 / 128.0F); - GL11.glVertex3f(this.posX + f2, this.posY, 0.0F); - GL11.glTexCoord2f(f / 128.0F, (f1 + 7.99F) / 128.0F); - GL11.glVertex3f(this.posX - f2, this.posY + 7.99F, 0.0F); - GL11.glTexCoord2f((f + f3 - 1.0F) / 128.0F, f1 / 128.0F); - GL11.glVertex3f(this.posX + f3 - 1.0F + f2, this.posY, 0.0F); - GL11.glTexCoord2f((f + f3 - 1.0F) / 128.0F, (f1 + 7.99F) / 128.0F); - GL11.glVertex3f(this.posX + f3 - 1.0F - f2, this.posY + 7.99F, 0.0F); - GL11.glEnd(); - return (float) this.charWidth[par1]; - } - - private ResourceLocation getUnicodePageLocation (int par1) - { - if (unicodePageLocations[par1] == null) - { - unicodePageLocations[par1] = new ResourceLocation("minecraft", String.format("textures/font/unicode_page_%02x.png", new Object[] { Integer.valueOf(par1) })); - } - return unicodePageLocations[par1]; - } - - /** - * Load one of the /font/glyph_XX.png into a new GL texture and store the texture ID in glyphTextureName array. - */ - private void loadGlyphTexture (int par1) - { - this.renderEngine.bindTexture(this.getUnicodePageLocation(par1)); - } - - /** - * Render a single Unicode character at current (posX,posY) location using one of the /font/glyph_XX.png files... - */ - private float renderUnicodeChar (char par1, boolean par2) - { - if (this.glyphWidth[par1] == 0) - { - return 0.0F; - } - else - { - int i = par1 / 256; - this.loadGlyphTexture(i); - int j = this.glyphWidth[par1] >>> 4; - int k = this.glyphWidth[par1] & 15; - float f = (float) j; - float f1 = (float) (k + 1); - float f2 = (float) (par1 % 16 * 16) + f; - float f3 = (float) ((par1 & 255) / 16 * 16); - float f4 = f1 - f - 0.02F; - float f5 = par2 ? 1.0F : 0.0F; - GL11.glBegin(GL11.GL_TRIANGLE_STRIP); - GL11.glTexCoord2f(f2 / 256.0F, f3 / 256.0F); - GL11.glVertex3f(this.posX + f5, this.posY, 0.0F); - GL11.glTexCoord2f(f2 / 256.0F, (f3 + 15.98F) / 256.0F); - GL11.glVertex3f(this.posX - f5, this.posY + 7.99F, 0.0F); - GL11.glTexCoord2f((f2 + f4) / 256.0F, f3 / 256.0F); - GL11.glVertex3f(this.posX + f4 / 2.0F + f5, this.posY, 0.0F); - GL11.glTexCoord2f((f2 + f4) / 256.0F, (f3 + 15.98F) / 256.0F); - GL11.glVertex3f(this.posX + f4 / 2.0F - f5, this.posY + 7.99F, 0.0F); - GL11.glEnd(); - return (f1 - f) / 2.0F + 1.0F; - } - } - - /** - * Draws the specified string with a shadow. - */ - public int drawStringWithShadow (String par1Str, int par2, int par3, int par4) - { - return this.drawString(par1Str, par2, par3, par4, true); - } - - /** - * Draws the specified string. - */ - public int drawString (String par1Str, int par2, int par3, int par4) - { - return this.drawString(par1Str, par2, par3, par4, false); - } - - /** - * Draws the specified string. Args: string, x, y, color, dropShadow - */ - public int drawString (String par1Str, int par2, int par3, int par4, boolean par5) - { - this.resetStyles(); - - if (this.bidiFlag) - { - par1Str = this.bidiReorder(par1Str); - } - - int l; - - if (par5) - { - l = this.renderString(par1Str, par2 + 1, par3 + 1, par4, true); - l = Math.max(l, this.renderString(par1Str, par2, par3, par4, false)); - } - else - { - l = this.renderString(par1Str, par2, par3, par4, false); - } - - return l; - } - - /** - * Apply Unicode Bidirectional Algorithm to string and return a new possibly reordered string for visual rendering. - */ - private String bidiReorder (String par1Str) - { - if (par1Str != null && Bidi.requiresBidi(par1Str.toCharArray(), 0, par1Str.length())) - { - Bidi bidi = new Bidi(par1Str, -2); - byte[] abyte = new byte[bidi.getRunCount()]; - String[] astring = new String[abyte.length]; - int i; - - for (int j = 0; j < abyte.length; ++j) - { - int k = bidi.getRunStart(j); - i = bidi.getRunLimit(j); - int l = bidi.getRunLevel(j); - String s1 = par1Str.substring(k, i); - abyte[j] = (byte) l; - astring[j] = s1; - } - - String[] astring1 = astring.clone(); - Bidi.reorderVisually(abyte, 0, astring, 0, abyte.length); - StringBuilder stringbuilder = new StringBuilder(); - i = 0; - - while (i < astring.length) - { - byte b0 = abyte[i]; - int i1 = 0; - - while (true) - { - if (i1 < astring1.length) - { - if (!astring1[i1].equals(astring[i])) - { - ++i1; - continue; - } - - b0 = abyte[i1]; - } - - if ((b0 & 1) == 0) - { - stringbuilder.append(astring[i]); - } - else - { - for (i1 = astring[i].length() - 1; i1 >= 0; --i1) - { - char c0 = astring[i].charAt(i1); - - if (c0 == 40) - { - c0 = 41; - } - else if (c0 == 41) - { - c0 = 40; - } - - stringbuilder.append(c0); - } - } - - ++i; - break; - } - } - - return stringbuilder.toString(); - } - else - { - return par1Str; - } - } - - /** - * Reset all style flag fields in the class to false; called at the start of string rendering - */ - private void resetStyles () - { - this.randomStyle = false; - this.boldStyle = false; - this.italicStyle = false; - this.underlineStyle = false; - this.strikethroughStyle = false; - } - - /** - * Render a single line string at the current (posX,posY) and update posX - */ - private void renderStringAtPos (String par1Str, boolean par2) - { - for (int i = 0; i < par1Str.length(); ++i) - { - char c0 = par1Str.charAt(i); - int j; - int k; - - if (c0 == 167 && i + 1 < par1Str.length()) - { - j = "0123456789abcdefklmnor".indexOf(par1Str.toLowerCase().charAt(i + 1)); - - if (j < 16) - { - this.randomStyle = false; - this.boldStyle = false; - this.strikethroughStyle = false; - this.underlineStyle = false; - this.italicStyle = false; - - if (j < 0 || j > 15) - { - j = 15; - } - - if (par2) - { - j += 16; - } - - k = this.colorCode[j]; - this.textColor = k; - GL11.glColor4f((float) (k >> 16) / 255.0F, (float) (k >> 8 & 255) / 255.0F, (float) (k & 255) / 255.0F, this.alpha); - } - else if (j == 16) - { - this.randomStyle = true; - } - else if (j == 17) - { - this.boldStyle = true; - } - else if (j == 18) - { - this.strikethroughStyle = true; - } - else if (j == 19) - { - this.underlineStyle = true; - } - else if (j == 20) - { - this.italicStyle = true; - } - else if (j == 21) - { - this.randomStyle = false; - this.boldStyle = false; - this.strikethroughStyle = false; - this.underlineStyle = false; - this.italicStyle = false; - GL11.glColor4f(this.red, this.blue, this.green, this.alpha); - } - - ++i; - } - else - { - j = ' '; - for (char c : ChatAllowedCharacters.allowedCharactersArray) - { - if (c == c0) - { - j = c0; - break; - } - } - - if (this.randomStyle && j > 0) - { - do - { - k = this.fontRandom.nextInt(ChatAllowedCharacters.allowedCharactersArray.length); - } while (this.charWidth[j + 32] != this.charWidth[k + 32]); - - j = k; - } - - float f = this.unicodeFlag ? 0.5F : 1.0F; - boolean flag1 = (j <= 0 || this.unicodeFlag) && par2; - - if (flag1) - { - this.posX -= f; - this.posY -= f; - } - float f1 = this.renderCharAtPos(j, c0, this.italicStyle); - - if (flag1) - { - this.posX += f; - this.posY += f; - } - - if (this.boldStyle) - { - this.posX += f; - - if (flag1) - { - this.posX -= f; - this.posY -= f; - } - - this.renderCharAtPos(j, c0, this.italicStyle); - this.posX -= f; - - if (flag1) - { - this.posX += f; - this.posY += f; - } - - ++f1; - } - - Tessellator tessellator; - - if (this.strikethroughStyle) - { - tessellator = Tessellator.instance; - GL11.glDisable(GL11.GL_TEXTURE_2D); - tessellator.startDrawingQuads(); - tessellator.addVertex((double) this.posX, (double) (this.posY + (float) (this.FONT_HEIGHT / 2)), 0.0D); - tessellator.addVertex((double) (this.posX + f1), (double) (this.posY + (float) (this.FONT_HEIGHT / 2)), 0.0D); - tessellator.addVertex((double) (this.posX + f1), (double) (this.posY + (float) (this.FONT_HEIGHT / 2) - 1.0F), 0.0D); - tessellator.addVertex((double) this.posX, (double) (this.posY + (float) (this.FONT_HEIGHT / 2) - 1.0F), 0.0D); - tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - } - - if (this.underlineStyle) - { - tessellator = Tessellator.instance; - GL11.glDisable(GL11.GL_TEXTURE_2D); - tessellator.startDrawingQuads(); - int l = this.underlineStyle ? -1 : 0; - tessellator.addVertex((double) (this.posX + (float) l), (double) (this.posY + (float) this.FONT_HEIGHT), 0.0D); - tessellator.addVertex((double) (this.posX + f1), (double) (this.posY + (float) this.FONT_HEIGHT), 0.0D); - tessellator.addVertex((double) (this.posX + f1), (double) (this.posY + (float) this.FONT_HEIGHT - 1.0F), 0.0D); - tessellator.addVertex((double) (this.posX + (float) l), (double) (this.posY + (float) this.FONT_HEIGHT - 1.0F), 0.0D); - tessellator.draw(); - GL11.glEnable(GL11.GL_TEXTURE_2D); - } - - this.posX += (float) ((int) f1); - } - } - } - - /** - * Render string either left or right aligned depending on bidiFlag - */ - private int renderStringAligned (String par1Str, int par2, int par3, int par4, int par5, boolean par6) - { - if (this.bidiFlag) - { - par1Str = this.bidiReorder(par1Str); - int i1 = this.getStringWidth(par1Str); - par2 = par2 + par4 - i1; - } - - return this.renderString(par1Str, par2, par3, par5, par6); - } - - /** - * Render single line string by setting GL color, current (posX,posY), and calling renderStringAtPos() - */ - private int renderString (String par1Str, int par2, int par3, int par4, boolean par5) - { - if (par1Str == null) - { - return 0; - } - else - { - if ((par4 & -67108864) == 0) - { - par4 |= -16777216; - } - - if (par5) - { - par4 = (par4 & 16579836) >> 2 | par4 & -16777216; - } - - this.red = (float) (par4 >> 16 & 255) / 255.0F; - this.blue = (float) (par4 >> 8 & 255) / 255.0F; - this.green = (float) (par4 & 255) / 255.0F; - this.alpha = (float) (par4 >> 24 & 255) / 255.0F; - boolean gl_blend = GL11.glIsEnabled(GL11.GL_BLEND); - if (!gl_blend) GL11.glEnable(GL11.GL_BLEND); - GL11.glColor4f(this.red, this.blue, this.green, this.alpha); - this.posX = (float) par2; - this.posY = (float) par3; - this.renderStringAtPos(par1Str, par5); - if (!gl_blend) GL11.glDisable(GL11.GL_BLEND); - return (int) this.posX; - } - } - - /** - * Returns the width of this string. Equivalent of FontMetrics.stringWidth(String s). - */ - public int getStringWidth (String par1Str) - { - if (par1Str == null) - { - return 0; - } - else - { - int i = 0; - boolean flag = false; - - for (int j = 0; j < par1Str.length(); ++j) - { - char c0 = par1Str.charAt(j); - int k = this.getCharWidth(c0); - - if (k < 0 && j < par1Str.length() - 1) - { - ++j; - c0 = par1Str.charAt(j); - - if (c0 != 108 && c0 != 76) - { - if (c0 == 114 || c0 == 82) - { - flag = false; - } - } - else - { - flag = true; - } - - k = 0; - } - - i += k; - - if (flag) - { - ++i; - } - } - - return i; - } - } - - /** - * Returns the width of this character as rendered. - */ - public int getCharWidth (char par1) - { - if (par1 == 167) - { - return -1; - } - else if (par1 == 32) - { - return 4; - } - else - { - int i; - if (ChatAllowedCharacters.isAllowedCharacter(par1)) - i = par1; - else - { - i = 69; - logger.error("dont send bad chat characters to my font renderer!"); - } - - if (i >= 0 && !this.unicodeFlag) - { - return this.charWidth[i + 32]; - } - else if (this.glyphWidth[par1] != 0) - { - int j = this.glyphWidth[par1] >>> 4; - int k = this.glyphWidth[par1] & 15; - - if (k > 7) - { - k = 15; - j = 0; - } - - ++k; - return (k - j) / 2 + 1; - } - else - { - return 0; - } - } - } - - /** - * Trims a string to fit a specified Width. - */ - public String trimStringToWidth (String par1Str, int par2) - { - return this.trimStringToWidth(par1Str, par2, false); - } - - /** - * Trims a string to a specified width, and will reverse it if par3 is set. - */ - public String trimStringToWidth (String par1Str, int par2, boolean par3) - { - StringBuilder stringbuilder = new StringBuilder(); - int j = 0; - int k = par3 ? par1Str.length() - 1 : 0; - int l = par3 ? -1 : 1; - boolean flag1 = false; - boolean flag2 = false; - - for (int i1 = k; i1 >= 0 && i1 < par1Str.length() && j < par2; i1 += l) - { - char c0 = par1Str.charAt(i1); - int j1 = this.getCharWidth(c0); - - if (flag1) - { - flag1 = false; - - if (c0 != 108 && c0 != 76) - { - if (c0 == 114 || c0 == 82) - { - flag2 = false; - } - } - else - { - flag2 = true; - } - } - else if (j1 < 0) - { - flag1 = true; - } - else - { - j += j1; - - if (flag2) - { - ++j; - } - } - - if (j > par2) - { - break; - } - - if (par3) - { - stringbuilder.insert(0, c0); - } - else - { - stringbuilder.append(c0); - } - } - - return stringbuilder.toString(); - } - - /** - * Remove all newline characters from the end of the string - */ - private String trimStringNewline (String par1Str) - { - while (par1Str != null && par1Str.endsWith("\n")) - { - par1Str = par1Str.substring(0, par1Str.length() - 1); - } - - return par1Str; - } - - /** - * Splits and draws a String with wordwrap (maximum length is parameter k) - */ - public void drawSplitString (String par1Str, int par2, int par3, int par4, int par5) - { - this.resetStyles(); - this.textColor = par5; - par1Str = this.trimStringNewline(par1Str); - this.renderSplitString(par1Str, par2, par3, par4, false); - } - - /** - * Perform actual work of rendering a multi-line string with wordwrap and with darker drop shadow color if flag is - * set - */ - @SuppressWarnings("raw") - private void renderSplitString (String par1Str, int par2, int par3, int par4, boolean par5) - { - List list = this.listFormattedStringToWidth(par1Str, par4); - - for (Iterator iterator = list.iterator(); iterator.hasNext(); par3 += this.FONT_HEIGHT) - { - String s1 = iterator.next(); - this.renderStringAligned(s1, par2, par3, par4, this.textColor, par5); - } - } - - /** - * Returns the width of the wordwrapped String (maximum length is parameter k) - */ - public int splitStringWidth (String par1Str, int par2) - { - return this.FONT_HEIGHT * this.listFormattedStringToWidth(par1Str, par2).size(); - } - - /** - * Set unicodeFlag controlling whether strings should be rendered with Unicode fonts instead of the default.png - * font. - */ - public void setUnicodeFlag (boolean par1) - { - this.unicodeFlag = par1; - } - - /** - * Get unicodeFlag controlling whether strings should be rendered with Unicode fonts instead of the default.png - * font. - */ - public boolean getUnicodeFlag () - { - return this.unicodeFlag; - } - - /** - * Set bidiFlag to control if the Unicode Bidirectional Algorithm should be run before rendering any string. - */ - public void setBidiFlag (boolean par1) - { - this.bidiFlag = par1; - } - - /** - * Breaks a string into a list of pieces that will fit a specified width. - */ - public List listFormattedStringToWidth (String par1Str, int par2) - { - return Arrays.asList(this.wrapFormattedStringToWidth(par1Str, par2).split("\n")); - } - - /** - * Inserts newline and formatting into a string to wrap it within the specified width. - */ - String wrapFormattedStringToWidth (String par1Str, int par2) - { - int j = this.sizeStringToWidth(par1Str, par2); - - if (par1Str.length() <= j) - { - return par1Str; - } - else - { - String s1 = par1Str.substring(0, j); - char c0 = par1Str.charAt(j); - boolean flag = c0 == 32 || c0 == 10; - String s2 = getFormatFromString(s1) + par1Str.substring(j + (flag ? 1 : 0)); - return s1 + "\n" + this.wrapFormattedStringToWidth(s2, par2); - } - } - - /** - * Determines how many characters from the string will fit into the specified width. - */ - @SuppressWarnings("fallthrough") - private int sizeStringToWidth (String par1Str, int par2) - { - int j = par1Str.length(); - int k = 0; - int l = 0; - int i1 = -1; - - for (boolean flag = false; l < j; ++l) - { - char c0 = par1Str.charAt(l); - - switch (c0) - { - case 10: - --l; - break; - case 167: - if (l < j - 1) - { - ++l; - char c1 = par1Str.charAt(l); - - if (c1 != 108 && c1 != 76) - { - if (c1 == 114 || c1 == 82 || isFormatColor(c1)) - { - flag = false; - } - } - else - { - flag = true; - } - } - - break; - case 32: - i1 = l; - default: - k += this.getCharWidth(c0); - - if (flag) - { - ++k; - } - } - - if (c0 == 10) - { - ++l; - i1 = l; - break; - } - - if (k > par2) - { - break; - } - } - - return l != j && i1 != -1 && i1 < l ? i1 : l; - } - - /** - * Checks if the char code is a hexadecimal character, used to set colour. - */ - private static boolean isFormatColor (char par0) - { - return par0 >= 48 && par0 <= 57 || par0 >= 97 && par0 <= 102 || par0 >= 65 && par0 <= 70; - } - - /** - * Checks if the char code is O-K...lLrRk-o... used to set special formatting. - */ - private static boolean isFormatSpecial (char par0) - { - return par0 >= 107 && par0 <= 111 || par0 >= 75 && par0 <= 79 || par0 == 114 || par0 == 82; - } - - /** - * Digests a string for nonprinting formatting characters then returns a string containing only that formatting. - */ - private static String getFormatFromString (String par0Str) - { - String s1 = ""; - int i = -1; - int j = par0Str.length(); - - while ((i = par0Str.indexOf(167, i + 1)) != -1) - { - if (i < j - 1) - { - char c0 = par0Str.charAt(i + 1); - - if (isFormatColor(c0)) - { - s1 = "\u00a7" + c0; - } - else if (isFormatSpecial(c0)) - { - s1 = s1 + "\u00a7" + c0; - } - } - } - - return s1; - } - - /** - * Get bidiFlag that controls if the Unicode Bidirectional Algorithm should be run before rendering any string - */ - public boolean getBidiFlag () - { - return this.bidiFlag; - } - -} diff --git a/src/mantle/client/gui/GuiManual.java b/src/mantle/client/gui/GuiManual.java deleted file mode 100644 index a07492f..0000000 --- a/src/mantle/client/gui/GuiManual.java +++ /dev/null @@ -1,201 +0,0 @@ -package mantle.client.gui; - -import mantle.books.BookData; -import mantle.client.MProxyClient; -import mantle.client.RenderItemCopy; -import mantle.client.SmallFontRenderer; -import mantle.client.pages.BookPage; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class GuiManual extends GuiScreen -{ - ItemStack itemstackBook; - Document manual; - public RenderItemCopy renderitem = new RenderItemCopy(); - int bookImageWidth = 206; - int bookImageHeight = 200; - int bookTotalPages = 1; - int currentPage; - int maxPages; - BookData bData; - - private TurnPageButton buttonNextPage; - private TurnPageButton buttonPreviousPage; - private static ResourceLocation bookRight;// = new ResourceLocation("mantle", "textures/gui/bookright.png"); - private static ResourceLocation bookLeft;// = new ResourceLocation("mantle", "textures/gui/bookleft.png"); - - BookPage pageLeft; - BookPage pageRight; - - public SmallFontRenderer fonts = MProxyClient.smallFontRenderer; - - public GuiManual(ItemStack stack, BookData data) - { - this.mc = Minecraft.getMinecraft(); - this.itemstackBook = stack; - currentPage = 0; //Stack page - manual = data.getDoc(); - if (data.font != null) - this.fonts = data.font; - bookLeft = data.leftImage; - bookRight = data.rightImage; - this.bData = data; - - //renderitem.renderInFrame = true; - } - - /*@Override - public void setWorldAndResolution (Minecraft minecraft, int w, int h) - { - this.guiParticles = new GuiParticle(minecraft); - this.mc = minecraft; - this.width = w; - this.height = h; - this.buttonList.clear(); - this.initGui(); - }*/ - - @SuppressWarnings("unchecked") - public void initGui () - { - maxPages = manual.getElementsByTagName("page").getLength(); - updateText(); - int xPos = (this.width) / 2; //TODO Width? - //TODO buttonList - this.buttonList.add(this.buttonNextPage = new TurnPageButton(1, xPos + bookImageWidth - 50, 180, true, bData)); - this.buttonList.add(this.buttonPreviousPage = new TurnPageButton(2, xPos - bookImageWidth + 24, 180, false, bData)); - } - - protected void actionPerformed (GuiButton button) - { - if (button.enabled) - { - if (button.id == 1) - currentPage += 2; - if (button.id == 2) - currentPage -= 2; - - updateText(); - } - } - - void updateText () - { - if (maxPages % 2 == 1) - { - if (currentPage > maxPages) - currentPage = maxPages; - } - else - { - if (currentPage >= maxPages) - currentPage = maxPages - 2; - } - if (currentPage % 2 == 1) - currentPage--; - if (currentPage < 0) - currentPage = 0; - - NodeList nList = manual.getElementsByTagName("page"); - - Node node = nList.item(currentPage); - if (node.getNodeType() == Node.ELEMENT_NODE) - { - Element element = (Element) node; - Class clazz = MProxyClient.getPageClass(element.getAttribute("type")); - if (clazz != null) - { - try - { - pageLeft = clazz.newInstance(); - pageLeft.init(this, 0); - pageLeft.readPageFromXML(element); - } - catch (Exception e) - { - } - } - else - { - pageLeft = null; - } - } - - node = nList.item(currentPage + 1); - if (node != null && node.getNodeType() == Node.ELEMENT_NODE) - { - Element element = (Element) node; - Class clazz = MProxyClient.getPageClass(element.getAttribute("type")); - if (clazz != null) - { - try - { - pageRight = clazz.newInstance(); - pageRight.init(this, 1); - pageRight.readPageFromXML(element); - } - catch (Exception e) - { - } - } - else - { - pageLeft = null; - } - } - else - { - pageRight = null; - } - } - - public void drawScreen (int par1, int par2, float par3) - { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(bookRight); - int localWidth = (this.width / 2); - byte localHeight = 8; - this.drawTexturedModalRect(localWidth, localHeight, 0, 0, this.bookImageWidth, this.bookImageHeight); - - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(bookLeft); - localWidth = localWidth - this.bookImageWidth; - this.drawTexturedModalRect(localWidth, localHeight, 256 - this.bookImageWidth, 0, this.bookImageWidth, this.bookImageHeight); - - super.drawScreen(par1, par2, par3); //16, 12, 220, 12 - - if (pageLeft != null) - pageLeft.renderBackgroundLayer(localWidth + 16, localHeight + 12); - if (pageRight != null) - pageRight.renderBackgroundLayer(localWidth + 220, localHeight + 12); - if (pageLeft != null) - pageLeft.renderContentLayer(localWidth + 16, localHeight + 12, bData.isTranslatable); - if (pageRight != null) - pageRight.renderContentLayer(localWidth + 220, localHeight + 12, bData.isTranslatable); - - } - - public Minecraft getMC () - { - return mc; - } - - public boolean doesGuiPauseGame () - { - return false; - } -} diff --git a/src/mantle/client/gui/TurnPageButton.java b/src/mantle/client/gui/TurnPageButton.java deleted file mode 100644 index 82f0ffd..0000000 --- a/src/mantle/client/gui/TurnPageButton.java +++ /dev/null @@ -1,56 +0,0 @@ -package mantle.client.gui; - -import static mantle.lib.CoreRepo.logger; -import mantle.books.BookData; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.util.ResourceLocation; - -import org.lwjgl.opengl.GL11; - -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -@SideOnly(Side.CLIENT) -public class TurnPageButton extends GuiButton -{ - /** - * True for pointing right (next page), false for pointing left (previous page). - */ - private final boolean nextPage; - private static ResourceLocation background;// = new ResourceLocation("tinker", "textures/gui/bookleft.png"); - - public TurnPageButton(int par1, int par2, int par3, boolean par4, BookData data) - { - super(par1, par2, par3, 23, 13, ""); - this.nextPage = par4; - background = data.leftImage; - } - - /** - * Draws this button to the screen. - */ - public void drawButton (Minecraft par1Minecraft, int par2, int par3) - { - if (this.visible) - { - boolean var4 = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width && par3 < this.yPosition + this.height; - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - par1Minecraft.getTextureManager().bindTexture(background); - int var5 = 0; - int var6 = 192; - - if (var4) - { - var5 += 23; - } - - if (!this.nextPage) - { - var6 += 13; - } - - this.drawTexturedModalRect(this.xPosition, this.yPosition, var5, var6, 23, 13); - } - } -} diff --git a/src/mantle/client/pages/BlankPage.java b/src/mantle/client/pages/BlankPage.java deleted file mode 100644 index d9fa597..0000000 --- a/src/mantle/client/pages/BlankPage.java +++ /dev/null @@ -1,18 +0,0 @@ -package mantle.client.pages; - -import org.w3c.dom.Element; - -public class BlankPage extends BookPage -{ - - @Override - public void readPageFromXML (Element element) - { - } - - @Override - public void renderContentLayer (int localwidth, int localheight, boolean isTranslatable) - { - } - -} diff --git a/src/mantle/client/pages/BookPage.java b/src/mantle/client/pages/BookPage.java deleted file mode 100644 index f9359cd..0000000 --- a/src/mantle/client/pages/BookPage.java +++ /dev/null @@ -1,25 +0,0 @@ -package mantle.client.pages; - -import mantle.client.gui.GuiManual; - -import org.w3c.dom.Element; - -public abstract class BookPage -{ - protected GuiManual manual; - protected int side; - - public void init (GuiManual manual, int side) - { - this.manual = manual; - this.side = side; - } - - public abstract void readPageFromXML (Element element); - - public void renderBackgroundLayer (int localwidth, int localheight) - { - } - - public abstract void renderContentLayer (int localwidth, int localheight, boolean isTranslatable); -} diff --git a/src/mantle/client/pages/ContentsTablePage.java b/src/mantle/client/pages/ContentsTablePage.java deleted file mode 100644 index 62a0bec..0000000 --- a/src/mantle/client/pages/ContentsTablePage.java +++ /dev/null @@ -1,64 +0,0 @@ -package mantle.client.pages; - -import mantle.lib.client.MantleClientRegistry; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class ContentsTablePage extends BookPage -{ - String text; - String[] iconText; - ItemStack[] icons; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("text"); - if (nodes != null) - text = nodes.item(0).getTextContent(); - - nodes = element.getElementsByTagName("link"); - iconText = new String[nodes.getLength()]; - icons = new ItemStack[nodes.getLength()]; - for (int i = 0; i < nodes.getLength(); i++) - { - NodeList children = nodes.item(i).getChildNodes(); - iconText[i] = children.item(1).getTextContent(); - icons[i] = MantleClientRegistry.getManualIcon(children.item(3).getTextContent()); - } - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable) - { - if (text != null) - { - if (isTranslatable) - text = StatCollector.translateToLocal(text); - manual.fonts.drawString("\u00a7n" + text, localWidth + 25 + manual.fonts.getStringWidth(text) / 2, localHeight + 4, 0); - } - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - RenderHelper.enableGUIStandardItemLighting(); - manual.renderitem.zLevel = 100; - for (int i = 0; i < icons.length; i++) - { - manual.renderitem.renderItemIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i], localWidth + 16, localHeight + 18 * i + 18); - int yOffset = 18; - if (isTranslatable) - iconText[i] = StatCollector.translateToLocal(iconText[i]); - - if (iconText[i].length() > 40) - yOffset = 13; - manual.fonts.drawString(iconText[i], localWidth + 38, localHeight + 18 * i + yOffset, 0); - } - manual.renderitem.zLevel = 0; - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - } -} diff --git a/src/mantle/client/pages/CraftingPage.java b/src/mantle/client/pages/CraftingPage.java deleted file mode 100644 index 4c62aa2..0000000 --- a/src/mantle/client/pages/CraftingPage.java +++ /dev/null @@ -1,107 +0,0 @@ -package mantle.client.pages; - -import mantle.lib.client.MantleClientRegistry; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class CraftingPage extends BookPage -{ - String text; - String size; - ItemStack[] icons; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("text"); - if (nodes != null) - text = nodes.item(0).getTextContent(); - - nodes = element.getElementsByTagName("name"); - if (nodes != null) - icons = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent()); - - nodes = element.getElementsByTagName("size"); - if (nodes != null) - size = nodes.item(0).getTextContent(); - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable) - { - if (isTranslatable) - text = StatCollector.translateToLocal(text); - if (size.equals("two")) - drawCraftingPage(text, icons, 2, localWidth, localHeight + 12); - if (size.equals("three")) - drawCraftingPage(text, icons, 3, localWidth + (side != 1 ? 6 : 0), localHeight + 12); - } - - public void drawCraftingPage (String info, ItemStack[] icons, int recipeSize, int localWidth, int localHeight) - { - if (info != null) - manual.fonts.drawString("\u00a7n" + info, localWidth + 50, localHeight + 4, 0); - - GL11.glScalef(2f, 2f, 2f); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - RenderHelper.enableGUIStandardItemLighting(); - manual.renderitem.zLevel = 100; - - if (recipeSize == 2) - { - manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 126) / 2, (localHeight + 68) / 2); - if (icons[0].stackSize > 1) - manual.renderitem.renderItemOverlayIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 126) / 2, (localHeight + 68) / 2, String.valueOf(icons[0].stackSize)); - for (int i = 0; i < icons.length - 1; i++) - { - if (icons[i + 1] != null) - manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i + 1], (localWidth + 14 + 36 * (i % 2)) / 2, (localHeight + 36 * (i / 2) + 52) / 2); - } - } - - if (recipeSize == 3) - { - manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 138) / 2, (localHeight + 70) / 2); - if (icons[0].stackSize > 1) - manual.renderitem.renderItemOverlayIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 126) / 2, (localHeight + 68) / 2, String.valueOf(icons[0].stackSize)); - for (int i = 0; i < icons.length - 1; i++) - { - if (icons[i + 1] != null) - manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i + 1], (localWidth - 2 + 36 * (i % 3)) / 2, (localHeight + 36 * (i / 3) + 34) / 2); - } - } - - manual.renderitem.zLevel = 0; - GL11.glScalef(0.5F, 0.5F, 0.5F); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - } - - public void renderBackgroundLayer (int localwidth, int localheight) - { - if (size.equals("two")) - drawBackground(2, localwidth, localheight + 12); - - if (size.equals("three")) - drawBackground(3, localwidth + (side != 1 ? 6 : 0), localheight + 12); - } - - private static final ResourceLocation background = new ResourceLocation("mantle", "textures/gui/bookcrafting.png"); - - public void drawBackground (int size, int localWidth, int localHeight) - { - manual.getMC().getTextureManager().bindTexture(background); - if (size == 2) - manual.drawTexturedModalRect(localWidth + 8, localHeight + 46, 0, 116, 154, 78); - if (size == 3) - manual.drawTexturedModalRect(localWidth - 8, localHeight + 28, 0, 0, 183, 114); - } - -} diff --git a/src/mantle/client/pages/FurnacePage.java b/src/mantle/client/pages/FurnacePage.java deleted file mode 100644 index 5cbba2f..0000000 --- a/src/mantle/client/pages/FurnacePage.java +++ /dev/null @@ -1,65 +0,0 @@ -package mantle.client.pages; - -import mantle.lib.client.MantleClientRegistry; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class FurnacePage extends BookPage -{ - String text; - ItemStack[] icons; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("text"); - if (nodes != null) - text = nodes.item(0).getTextContent(); - - nodes = element.getElementsByTagName("recipe"); - if (nodes != null) - icons = MantleClientRegistry.getRecipeIcons(nodes.item(0).getTextContent()); - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable) - { - if (text != null) - { - if (isTranslatable) - text = StatCollector.translateToLocal(text); - manual.fonts.drawString("\u00a7n" + text, localWidth + 50, localHeight + 4, 0); - } - GL11.glScalef(2f, 2f, 2f); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - RenderHelper.enableGUIStandardItemLighting(); - manual.renderitem.zLevel = 100; - - manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, MantleClientRegistry.getManualIcon("coal"), (localWidth + 38) / 2, (localHeight + 110) / 2); - manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 106) / 2, (localHeight + 74) / 2); - manual.renderitem.renderItemAndEffectIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[1], (localWidth + 38) / 2, (localHeight + 38) / 2); - - if (icons[0].stackSize > 1) - manual.renderitem.renderItemOverlayIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[0], (localWidth + 106) / 2, (localHeight + 74) / 2, String.valueOf(icons[0].stackSize)); - - manual.renderitem.zLevel = 0; - GL11.glScalef(0.5F, 0.5F, 0.5F); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - } - - private static final ResourceLocation background = new ResourceLocation("mantle", "textures/gui/bookfurnace.png"); - - public void renderBackgroundLayer (int localWidth, int localHeight) - { - manual.getMC().getTextureManager().bindTexture(background); - manual.drawTexturedModalRect(localWidth + 32, localHeight + 32, 0, 0, 111, 114); - } -} diff --git a/src/mantle/client/pages/PicturePage.java b/src/mantle/client/pages/PicturePage.java deleted file mode 100644 index 7d3af30..0000000 --- a/src/mantle/client/pages/PicturePage.java +++ /dev/null @@ -1,63 +0,0 @@ -package mantle.client.pages; - -import mantle.lib.client.MantleClientRegistry; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; -import static mantle.lib.CoreRepo.logger; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class PicturePage extends BookPage -{ - String text; - String location; - ResourceLocation background; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("text"); - if (nodes != null) - text = nodes.item(0).getTextContent(); - nodes = element.getElementsByTagName("location"); - if (nodes != null) - { - location = nodes.item(0).getTextContent(); - background = new ResourceLocation(location); - if(background == null) - { - logger.warn(nodes.item(0).getTextContent() + " could not be found in the image cache(location)!"); - } - } - - //this borked stuffs somehow unless someone is interested in using it this stays disabled for now - /* nodes = element.getElementsByTagName("bookImage"); - if (nodes != null) - { - //TODO 1.7 null check all of this - background = MantleClientRegistry.imageCache.get(nodes.item(0).getTextContent()).resource; - if(background == null){ - logger.warn(nodes.item(0).getTextContent() + " could not be found in the image cache(bookimage)!"); - } - }*/ - - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable) - { - if (isTranslatable) - text = StatCollector.translateToLocal(text); - manual.fonts.drawSplitString(text, localWidth + 8, localHeight, 178, 0); - } - - public void renderBackgroundLayer (int localWidth, int localHeight) - { - if (background != null) - { - manual.getMC().getTextureManager().bindTexture(background); - } - //manual.getMC().renderEngine.bindTexture(location); - manual.drawTexturedModalRect(localWidth, localHeight + 12, 0, 0, 170, 144); - } -} diff --git a/src/mantle/client/pages/SectionPage.java b/src/mantle/client/pages/SectionPage.java deleted file mode 100644 index b1ca875..0000000 --- a/src/mantle/client/pages/SectionPage.java +++ /dev/null @@ -1,36 +0,0 @@ -package mantle.client.pages; - -import net.minecraft.util.StatCollector; - -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class SectionPage extends BookPage -{ - String title; - String body; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("title"); - if (nodes != null) - title = nodes.item(0).getTextContent(); - - nodes = element.getElementsByTagName("text"); - if (nodes != null) - body = nodes.item(0).getTextContent(); - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable) - { - if (isTranslatable) - { - title = StatCollector.translateToLocal(title); - body = StatCollector.translateToLocal(body); - } - manual.fonts.drawSplitString("\u00a7n" + title, localWidth + 70, localHeight + 4, 178, 0); - manual.fonts.drawSplitString(body, localWidth, localHeight + 16, 190, 0); - } -} diff --git a/src/mantle/client/pages/SidebarPage.java b/src/mantle/client/pages/SidebarPage.java deleted file mode 100644 index 13605d8..0000000 --- a/src/mantle/client/pages/SidebarPage.java +++ /dev/null @@ -1,65 +0,0 @@ -package mantle.client.pages; - -import mantle.lib.client.MantleClientRegistry; -import net.minecraft.client.renderer.RenderHelper; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; - -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class SidebarPage extends BookPage -{ - String text; - String[] iconText; - ItemStack[] icons; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("text"); - if (nodes != null) - text = nodes.item(0).getTextContent(); - - nodes = element.getElementsByTagName("item"); - iconText = new String[nodes.getLength()]; - icons = new ItemStack[nodes.getLength()]; - for (int i = 0; i < nodes.getLength(); i++) - { - NodeList children = nodes.item(i).getChildNodes(); - iconText[i] = children.item(1).getTextContent(); - icons[i] = MantleClientRegistry.getManualIcon(children.item(3).getTextContent()); - } - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable) - { - if (isTranslatable) - { - text = StatCollector.translateToLocal(text); - } - manual.fonts.drawSplitString(text, localWidth, localHeight, 178, 0); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - RenderHelper.enableGUIStandardItemLighting(); - manual.renderitem.zLevel = 100; - int offset = text.length() / 4 + 10; - for (int i = 0; i < icons.length; i++) - { - if (isTranslatable) - { - iconText[i] = StatCollector.translateToLocal(iconText[i]); - } - manual.renderitem.renderItemIntoGUI(manual.fonts, manual.getMC().renderEngine, icons[i], localWidth + 8, localHeight + 18 * i + offset); - int yOffset = 39; - if (iconText[i].length() > 40) - yOffset = 34; - manual.fonts.drawSplitString(iconText[i], localWidth + 30, localHeight + 18 * i + offset, 140, 0); - } - manual.renderitem.zLevel = 0; - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - } -} diff --git a/src/mantle/client/pages/TextPage.java b/src/mantle/client/pages/TextPage.java deleted file mode 100644 index 00c52fa..0000000 --- a/src/mantle/client/pages/TextPage.java +++ /dev/null @@ -1,27 +0,0 @@ -package mantle.client.pages; - -import net.minecraft.util.StatCollector; - -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class TextPage extends BookPage -{ - String text; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("text"); - if (nodes != null) - text = nodes.item(0).getTextContent(); - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean IsTranslatable) - { - if (IsTranslatable) - text = StatCollector.translateToLocal(text); - manual.fonts.drawSplitString(text, localWidth, localHeight, 178, 0); - } -} diff --git a/src/mantle/client/pages/TitlePage.java b/src/mantle/client/pages/TitlePage.java deleted file mode 100644 index b103bc6..0000000 --- a/src/mantle/client/pages/TitlePage.java +++ /dev/null @@ -1,27 +0,0 @@ -package mantle.client.pages; - -import net.minecraft.util.StatCollector; - -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - -public class TitlePage extends BookPage -{ - String text; - - @Override - public void readPageFromXML (Element element) - { - NodeList nodes = element.getElementsByTagName("text"); - if (nodes != null) - text = nodes.item(0).getTextContent(); - } - - @Override - public void renderContentLayer (int localWidth, int localHeight, boolean isTranslatable) - { - if (isTranslatable) - text = StatCollector.translateToLocal(text); - manual.fonts.drawSplitString(text, localWidth, localHeight, 178, 0); - } -} diff --git a/src/mantle/common/ComparisonHelper.java b/src/mantle/common/ComparisonHelper.java deleted file mode 100644 index 642bfc1..0000000 --- a/src/mantle/common/ComparisonHelper.java +++ /dev/null @@ -1,28 +0,0 @@ -package mantle.common; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public class ComparisonHelper -{ - public static boolean areEquivalent (Item item, Block block) - { - return item == Item.getItemFromBlock(block); - } - - public static boolean areEquivalent (Block block1, Block block2) - { - return block1 == block2; - } - - public static boolean areEquivalent (Item item1, Item item2) - { - return item1.equals(item2); - } - - public static boolean areEquivalent (ItemStack is1, ItemStack is2) - { - return is1.getItem() == is2.getItem(); - } -} diff --git a/src/mantle/common/IDDumps.java b/src/mantle/common/IDDumps.java deleted file mode 100644 index de437b3..0000000 --- a/src/mantle/common/IDDumps.java +++ /dev/null @@ -1,46 +0,0 @@ -package mantle.common; - -import static mantle.lib.CoreRepo.logger; -import mantle.lib.CoreConfig; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.potion.Potion; -import net.minecraft.world.biome.BiomeGenBase; - -public class IDDumps -{ - public static void dump(){ - if (CoreConfig.dumpBiomeIDs) - { - for (BiomeGenBase b : BiomeGenBase.getBiomeGenArray()) - { - if (b != null && b.biomeName != null) - { - logger.info("Biome ID & Name: " + b.biomeID + " " + b.biomeName); - } - } - } - if (CoreConfig.dumpPotionIDs) - { - for (Potion p : Potion.potionTypes) - { - if (p != null && p.getName() != null) - { - - logger.info("Potion ID & name: " + p.getId() + " " + p.getName()); - } - } - } - if (CoreConfig.dumpEnchantIDs) - { - for (Enchantment e : Enchantment.enchantmentsList) - { - if (e != null && e.getName() != null) - { - - logger.info("Enchantment ID & name: " + e.effectId + " " + e.getName()); - } - } - } - } - -} diff --git a/src/mantle/common/MProxyCommon.java b/src/mantle/common/MProxyCommon.java deleted file mode 100644 index 17a63bf..0000000 --- a/src/mantle/common/MProxyCommon.java +++ /dev/null @@ -1,32 +0,0 @@ -package mantle.common; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.world.World; -import cpw.mods.fml.common.network.IGuiHandler; - -public class MProxyCommon implements IGuiHandler -{ - public static int manualGuiID = -1; - - @Override - public Object getServerGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z) - { - if (ID < 0) - return null; - return null; - } - - @Override - public Object getClientGuiElement (int ID, EntityPlayer player, World world, int x, int y, int z) - { - return null; - } - - public void registerRenderer () - { - } - - public void readManuals () - { - } -} diff --git a/src/mantle/common/network/AbstractPacket.java b/src/mantle/common/network/AbstractPacket.java deleted file mode 100644 index 8d2b14a..0000000 --- a/src/mantle/common/network/AbstractPacket.java +++ /dev/null @@ -1,57 +0,0 @@ -package mantle.common.network; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import net.minecraft.entity.player.EntityPlayer; - -/** - * AbstractPacket class. Should be the parent of all packets wishing to use the - * PacketPipeline. - * - * @author sirgingalot - */ -public abstract class AbstractPacket -{ - - /** - * Encode the packet data into the ByteBuf stream. Complex data sets may - * need specific data handlers (See - * @link{cpw.mods.fml.common.network.ByteBuffUtils}) - * - * @param ctx - * channel context - * @param buffer - * the buffer to encode into - */ - public abstract void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer); - - /** - * Decode the packet data from the ByteBuf stream. Complex data sets may - * need specific data handlers (See - * @link{cpw.mods.fml.common.network.ByteBuffUtils}) - * - * @param ctx - * channel context - * @param buffer - * the buffer to decode from - */ - public abstract void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer); - - /** - * Handle a packet on the client side. Note this occurs after decoding has - * completed. - * - * @param player - * the player reference - */ - public abstract void handleClientSide (EntityPlayer player); - - /** - * Handle a packet on the server side. Note this occurs after decoding has - * completed. - * - * @param player - * the player reference - */ - public abstract void handleServerSide (EntityPlayer player); -} diff --git a/src/mantle/common/network/PacketUpdateTE.java b/src/mantle/common/network/PacketUpdateTE.java deleted file mode 100644 index 2ba216a..0000000 --- a/src/mantle/common/network/PacketUpdateTE.java +++ /dev/null @@ -1,78 +0,0 @@ -package mantle.common.network; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.PacketBuffer; -import net.minecraft.tileentity.TileEntity; - -public class PacketUpdateTE extends AbstractPacket -{ - private int x, y, z; - private NBTTagCompound data; - - public PacketUpdateTE() - { - - } - - public PacketUpdateTE(int x, int y, int z, NBTTagCompound data) - { - this.x = x; - this.y = y; - this.z = z; - this.data = data; - } - - @Override - public void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer) - { - PacketBuffer pbuff = new PacketBuffer(buffer); - pbuff.writeInt(x); - pbuff.writeShort(y); - pbuff.writeInt(z); - try - { - pbuff.writeNBTTagCompoundToBuffer(data); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - @Override - public void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer) - { - PacketBuffer pbuff = new PacketBuffer(buffer); - x = pbuff.readInt(); - y = pbuff.readShort(); - z = pbuff.readInt(); - try - { - data = pbuff.readNBTTagCompoundFromBuffer(); - } - catch (Exception e) - { - e.printStackTrace(); - } - } - - @Override - public void handleClientSide (EntityPlayer player) - { - TileEntity te = player.worldObj.getTileEntity(x, y, z); - - if (te != null) - { - te.readFromNBT(data); - } - } - - @Override - public void handleServerSide (EntityPlayer player) - { - } - -} diff --git a/src/mantle/crash/CallableSuppConfig.java b/src/mantle/crash/CallableSuppConfig.java deleted file mode 100644 index bee7045..0000000 --- a/src/mantle/crash/CallableSuppConfig.java +++ /dev/null @@ -1,32 +0,0 @@ -package mantle.crash; - -import cpw.mods.fml.common.ICrashCallable; - -/** - * Crash Callable for supported environments. - * - * @author Sunstrike - */ -public class CallableSuppConfig implements ICrashCallable -{ - - private String modId; - - public CallableSuppConfig(String modId) - { - this.modId = modId; - } - - @Override - public String call () throws Exception - { - return "Environment healthy."; - } - - @Override - public String getLabel () - { - return modId + " Environment"; - } - -} diff --git a/src/mantle/crash/CallableUnsuppConfig.java b/src/mantle/crash/CallableUnsuppConfig.java deleted file mode 100644 index f764c5f..0000000 --- a/src/mantle/crash/CallableUnsuppConfig.java +++ /dev/null @@ -1,40 +0,0 @@ -package mantle.crash; - -import java.util.List; - -import cpw.mods.fml.common.ICrashCallable; - -// Crash handler for when an unsupported mod is running alongside us -public class CallableUnsuppConfig implements ICrashCallable -{ - - private String modId; - private List modIds; - - public CallableUnsuppConfig(String modId, List modIds) - { - this.modId = modId; - this.modIds = modIds; - } - - @Override - public String getLabel () - { - return modId + " Environment"; - } - - @Override - public String call () throws Exception - { - String str = "DO NOT REPORT THIS CRASH! Unsupported mods in environment: "; - Boolean firstEntry = true; - for (String id : modIds) - { - str = str + (firstEntry ? id : ", " + id); - firstEntry = false; - } - - return str; - } - -} \ No newline at end of file diff --git a/src/mantle/debug/DebugData.java b/src/mantle/debug/DebugData.java deleted file mode 100644 index 86fd9f5..0000000 --- a/src/mantle/debug/DebugData.java +++ /dev/null @@ -1,25 +0,0 @@ -package mantle.debug; - -import net.minecraft.entity.player.EntityPlayer; - -/** - * Encapsulation for debug information - * - * @author Sunstrike - */ -public class DebugData -{ - - public final EntityPlayer player; - @SuppressWarnings("rawtypes") public final Class cl; - public final String[] strings; - - @SuppressWarnings("rawtypes") - public DebugData(EntityPlayer player, Class cl, String[] strings) - { - this.player = player; - this.cl = cl; - this.strings = strings; - } - -} diff --git a/src/mantle/debug/DebugHelper.java b/src/mantle/debug/DebugHelper.java deleted file mode 100644 index 304835e..0000000 --- a/src/mantle/debug/DebugHelper.java +++ /dev/null @@ -1,50 +0,0 @@ -package mantle.debug; - -import static mantle.lib.CoreConfig.debug_enableChat; -import static mantle.lib.CoreConfig.debug_enableConsole; -import static mantle.lib.CoreRepo.logger; -import mantle.player.PlayerUtils; -import net.minecraft.entity.player.EntityPlayer; - -/** - * IDebuggable helper - * - * @author Sunstrike - */ -public class DebugHelper -{ - - private DebugHelper() - { - // No instantiation - } - - public static void handleDebugData (DebugData data) - { - if (debug_enableChat) - handleChatDebug(data); - if (debug_enableConsole) - handleConsoleDebug(data); - } - - private static void handleChatDebug (DebugData data) - { - EntityPlayer player = data.player; - String prefix = "[" + data.cl.getSimpleName() + "] "; - for (String str : data.strings) - { - PlayerUtils.sendChatMessage(player, prefix + str); - } - } - - private static void handleConsoleDebug (DebugData data) - { - String player = data.player.getGameProfile().getName(); - String prefix = "[" + player + ":" + data.cl.getSimpleName() + "] "; - for (String str : data.strings) - { - logger.info(prefix + str); - } - } - -} diff --git a/src/mantle/debug/IDebuggable.java b/src/mantle/debug/IDebuggable.java deleted file mode 100644 index b972df9..0000000 --- a/src/mantle/debug/IDebuggable.java +++ /dev/null @@ -1,17 +0,0 @@ -package mantle.debug; - -import net.minecraft.entity.player.EntityPlayer; - -/** - * Interface for TEs which can be whacked with debug tools (sticks normally) for information. - * - * This is automatically used if the block containing the TE is a subclass of MantleBlock. - * - * @author Sunstrike - */ -public interface IDebuggable -{ - - public DebugData getDebugInfo (EntityPlayer player); - -} diff --git a/src/mantle/event/ManualOpenEvent.java b/src/mantle/event/ManualOpenEvent.java deleted file mode 100644 index de2931a..0000000 --- a/src/mantle/event/ManualOpenEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package mantle.event; - -import cpw.mods.fml.common.eventhandler.Event; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -public abstract class ManualOpenEvent extends Event { - - public ItemStack bookStack; - public EntityPlayer player; - - public ManualOpenEvent(ItemStack book, EntityPlayer player) { - this.bookStack = book; - this.player = player; - } - - public static class Pre extends ManualOpenEvent { - public Pre(ItemStack book, EntityPlayer player) { - super(book, player); - } - } - - public static class Post extends ManualOpenEvent { - public Post(ItemStack book, EntityPlayer player) { - super(book, player); - } - } -} diff --git a/src/mantle/event/Migration.java b/src/mantle/event/Migration.java deleted file mode 100644 index 39fad77..0000000 --- a/src/mantle/event/Migration.java +++ /dev/null @@ -1,88 +0,0 @@ -package mantle.event; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import cpw.mods.fml.common.ModContainer; -import cpw.mods.fml.common.event.FMLMissingMappingsEvent; -import cpw.mods.fml.common.event.FMLMissingMappingsEvent.MissingMapping; -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import static mantle.lib.CoreRepo.logger; -import java.util.List; -import java.util.Map; - -public abstract class Migration -{ - Map remapItem = Maps.newHashMap(); - Map remapBlock = Maps.newHashMap(); - List ignore = Lists.newArrayList(); - private ModContainer mod; - - private String modID; - - /* - * Store the mod ID so we can convert e.g "item" to "mod:item" later. - */ - public Migration(ModContainer m) - { - mod = m; - modID = m.getModId(); - } - - /* - * Add a new migration to the internal replacement map e.g. "olditem" -> "newitem" (without ID prefix!). - * Use an encapsulated object of form Map to store this. - * The prefix will be created using the ID given during construction during processing. - */ - public void addMigration (String old, Item newItem) - { - remapItem.put(modID + ":" + old, newItem); - } - - /* - * Add a new migration to the internal replacement map e.g. "olditem" -> "newitem" (without ID prefix!). - * Use an encapsulated object of form Map to store this. - * The prefix will be created using the ID given during construction during processing. - */ - public void addMigration (String old, Block newBlock) - { - remapBlock.put(modID + ":" + old, newBlock); - } - /* - * Register an old ID that's been removed entirely. This isn't suitable for renaming operations! - * Store this in a List seperate to the rename mapping. - * @param id ID to be removed (without ID prefix!). - */ - public void addRemoval (String id) - { - ignore.add(modID + ":" + id); - }; - - /* - * This must be called from your mod's main class as it requires @EventHandler notation - * This works on the assumption the FML event will have a list of string IDs that are missing. - * During this phase, check for old IDs and remap as needed, or destroy ones marked for removal. - */ - public void processMigrationEvent (FMLMissingMappingsEvent event) { - if ((!remapBlock.isEmpty() || !remapItem.isEmpty())) { - event.applyModContainer(mod); - List l = event.get(); - if(l != null) - { - for (MissingMapping miss : event.get()) { - if (remapItem.containsKey(miss.name)) - miss.remap(remapItem.get(miss.name)); - else if (remapBlock.containsKey(miss.name)) - miss.remap(remapBlock.get(miss.name)); - else if (ignore.contains(miss.name)) - miss.ignore(); - } - } - else - { - logger.error("migration list from FML empty for mod " + modID); - } - - } - } -} \ No newline at end of file diff --git a/src/mantle/items/ItemUtils.java b/src/mantle/items/ItemUtils.java deleted file mode 100644 index e863b71..0000000 --- a/src/mantle/items/ItemUtils.java +++ /dev/null @@ -1,16 +0,0 @@ -package mantle.items; - -import net.minecraft.item.Item; -import cpw.mods.fml.common.registry.GameData; - -public class ItemUtils -{ - public static String getUniqueName (Item item) - { - return GameData.getItemRegistry().getNameForObject(item); - } - public static Item getItemFromUniqueName (String uniqueName) - { - return GameData.getItemRegistry().getObject(uniqueName); - } -} diff --git a/src/mantle/items/Manual.java b/src/mantle/items/Manual.java deleted file mode 100644 index 521432e..0000000 --- a/src/mantle/items/Manual.java +++ /dev/null @@ -1,77 +0,0 @@ -package mantle.items; - -import net.minecraftforge.common.MinecraftForge; - -import mantle.event.ManualOpenEvent; - -import java.util.List; - -import mantle.Mantle; -import mantle.books.BookDataStore; -import mantle.items.abstracts.CraftingItem; -import mantle.lib.CoreRepo; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public class Manual extends CraftingItem -{ - - public final String modID; - static String[] name = new String[] { "beginner", "toolstation", "smeltery", "diary" }; - static String[] textureName = new String[] { "tinkerbook_diary", "tinkerbook_toolstation", "tinkerbook_smeltery", "tinkerbook_blue" }; - - public Manual() - { - super(name, textureName, "", "mantle", null); - modID = CoreRepo.modId; - } - - public void updateManual () - { - updateData(new String[] { "test" }, new String[] { "mantlebook_blue" }, "", "mantle"); - } - - public Manual(String[] name, String[] textureName, String folder, String modTexturePrefix, CreativeTabs tab, String modID) - { - super(name, textureName, "", "mantle", tab); - this.modID = modID; - } - - @Override - public ItemStack onItemRightClick (ItemStack stack, World world, EntityPlayer player) - { - ManualOpenEvent.Pre preOpenEvent = new ManualOpenEvent.Pre(stack, player); - MinecraftForge.EVENT_BUS.post(preOpenEvent); - - player.openGui(Mantle.instance, mantle.client.MProxyClient.manualGuiID, world, 0, 0, 0); - ManualOpenEvent.Post postOpenEvent = new ManualOpenEvent.Post(stack, player); - MinecraftForge.EVENT_BUS.post(postOpenEvent); - - return stack; - } - - @Override - @SideOnly(Side.CLIENT) - @SuppressWarnings({"unchecked", "rawtypes"}) - public void addInformation (ItemStack stack, EntityPlayer player, List list, boolean par4) - { - list.add("\u00a7o" + StatCollector.translateToLocal(BookDataStore.getBookfromID(stack.getMetadata()).toolTip)); - } - - @Override - public String getUnlocalizedName () - { - return modID + ":" + super.getUnlocalizedName(); - } - - @Override - public String getUnlocalizedName (ItemStack par1ItemStack) - { - return super.getUnlocalizedName(par1ItemStack); - } -} diff --git a/src/mantle/items/abstracts/CraftingItem.java b/src/mantle/items/abstracts/CraftingItem.java deleted file mode 100644 index 88b23f6..0000000 --- a/src/mantle/items/abstracts/CraftingItem.java +++ /dev/null @@ -1,81 +0,0 @@ -package mantle.items.abstracts; - -import java.util.List; - -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.util.MathHelper; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public class CraftingItem extends Item -{ - public String modTexPrefix; - public String[] textureNames; - public String[] unlocalizedNames; - public String folder; - public IIcon[] icons; - - public CraftingItem(String[] names, String[] tex, String folder, String modTexturePrefix, CreativeTabs tab) - { - super(); - this.modTexPrefix = modTexturePrefix; - if (tab != null) - { - this.setCreativeTab(tab); - } - this.setMaxDurability(0); - this.setHasSubtypes(true); - this.textureNames = tex; - this.unlocalizedNames = names; - this.folder = folder; - } - - public void updateData (String[] names, String[] tex, String folder, String modTexturePrefix) - { - this.modTexPrefix = modTexturePrefix; - this.textureNames = tex; - this.unlocalizedNames = names; - this.folder = folder; - } - - @SideOnly(Side.CLIENT) - public IIcon getIconFromDamage (int meta) - { - int arr = MathHelper.clamp_int(meta, 0, unlocalizedNames.length); - if(arr >= icons.length) - return icons[0]; - return icons[arr]; - } - - @Override - @SideOnly(Side.CLIENT) - public void registerIcons (IIconRegister iconRegister) - { - this.icons = new IIcon[textureNames.length]; - - for (int i = 0; i < this.icons.length; ++i) - { - if (!(textureNames[i].equals(""))) - this.icons[i] = iconRegister.registerIcon(modTexPrefix + ":" + folder + textureNames[i]); - } - } - - public String getUnlocalizedName (ItemStack stack) - { - int arr = MathHelper.clamp_int(stack.getMetadata(), 0, unlocalizedNames.length); - return getUnlocalizedName() + "." + unlocalizedNames[arr]; - } - - @SuppressWarnings({"unchecked","rawtypes"}) - public void getSubItems (Item b, CreativeTabs tab, List list) - { - for (int i = 0; i < unlocalizedNames.length; i++) - if (!(textureNames[i].equals(""))) - list.add(new ItemStack(b, 1, i)); - } - -} diff --git a/src/mantle/items/iface/IDebugItem.java b/src/mantle/items/iface/IDebugItem.java deleted file mode 100644 index bfb30fa..0000000 --- a/src/mantle/items/iface/IDebugItem.java +++ /dev/null @@ -1,6 +0,0 @@ -package mantle.items.iface; - -public interface IDebugItem -{ - // Will do more later; this is here for now to enable mods to use the debug stick functionality with their own debug items/tools. -} diff --git a/src/mantle/lib/CoreConfig.java b/src/mantle/lib/CoreConfig.java deleted file mode 100644 index 71fbe82..0000000 --- a/src/mantle/lib/CoreConfig.java +++ /dev/null @@ -1,104 +0,0 @@ -package mantle.lib; - -import static mantle.lib.CoreRepo.logger; -import static mantle.lib.CoreRepo.modId; - -import java.io.File; -import java.io.IOException; - -import org.apache.commons.io.FilenameUtils; - -import mantle.books.external.ZipLoader; -import net.minecraftforge.common.config.Configuration; - -/** - * Mantle configuration handler - * - * Stores configuration data for Mantle, and handles save/load. - * - * @author Sunstrike - */ -public class CoreConfig -{ - static Configuration config; - public static File configFolder; - - /** - * Loads state from the configuration folder. - * - * @param mainConfigFolder Configuration folder (as a Java File) - */ - public static void loadConfiguration (File mainConfigFolder) - { - logger.info("Loading configuration from disk."); - try - { - configFolder = new File(mainConfigFolder.getCanonicalPath(), "SlimeKnights"); - if (!configFolder.exists()) - configFolder.mkdirs(); - } - catch (IOException e) - { - logger.error("Error getting/creating Mantle configuration directory: " + e.getMessage()); - } - - config = new Configuration(new File(configFolder, (modId + ".cfg"))); - config.load(); - - silenceEnvChecks = config.get("Environment", "unsupportedLogging", silenceEnvChecks).getBoolean(silenceEnvChecks); - - debug_enableConsole = config.get("DebugHelpers", "enableConsole", debug_enableConsole).getBoolean(debug_enableConsole); - debug_enableChat = config.get("DebugHelpers", "enableChat", debug_enableChat).getBoolean(debug_enableChat); - - dumpBiomeIDs = config.get("DebugHelpers", "Dump BIOME ID's in log", dumpBiomeIDs).getBoolean(dumpBiomeIDs); - dumpPotionIDs = config.get("DebugHelpers", "Dump POTION ID's in log", dumpPotionIDs).getBoolean(dumpPotionIDs); - dumpEnchantIDs = config.get("DebugHelpers", "Dump ENCHANT ID's in log", dumpEnchantIDs).getBoolean(dumpEnchantIDs); - dumpRecipeConflicts = config.get("DebugHelpers", "Dump Recipe Conflicts in log when server starts",dumpRecipeConflicts).getBoolean(dumpRecipeConflicts); - - //check for debugging overrides in system environment - checkSysOverrides(); - if(config.hasChanged()) - config.save(); - logger.info("Configuration load completed."); - } - - /** - * Checks for MANTLE_DBGCONSOLE/CHAT config overrides in system environment for compile time testing, and other dev work. - **/ - private static void checkSysOverrides () - { - if (System.getenv("MANTLE_DBGCONSOLE") != null) - { - debug_enableConsole = true; - logger.info("Mantle Console debugging override enabled via system properties."); - } - if (System.getenv("MANTLE_DBGCHAT") != null) - { - debug_enableChat = true; - logger.info("Mantle Chat debugging override enabled via system properties."); - } - } - - public static void loadBookLocations () - { - for (File f : configFolder.listFiles()) - { - if(f.isFile() && FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase("zip")) - ZipLoader.loadZip(f); - } - } - - // BEGIN CONFIG VARS - // Env Checks - public static boolean silenceEnvChecks = false; - - // Debug Helpers - public static boolean debug_enableConsole = false; - public static boolean debug_enableChat = false; - public static boolean dumpBiomeIDs = false; - public static boolean dumpPotionIDs = false; - public static boolean dumpEnchantIDs = false; - public static boolean dumpRecipeConflicts = false; - - -} diff --git a/src/mantle/lib/CoreRepo.java b/src/mantle/lib/CoreRepo.java deleted file mode 100644 index ab6a379..0000000 --- a/src/mantle/lib/CoreRepo.java +++ /dev/null @@ -1,22 +0,0 @@ -package mantle.lib; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * Mantle object repository - * - * Storage area for objects accessible throughout Mantle, such as loggers - * - * @author Sunstrike - */ -public final class CoreRepo -{ - - public static final String modId = "Mantle"; - public static final String modName = "Mantle"; - public static final String modVersion = "${version}"; - - public static final Logger logger = LogManager.getLogger("Mantle"); - -} diff --git a/src/mantle/lib/TabTools.java b/src/mantle/lib/TabTools.java deleted file mode 100644 index 489edb6..0000000 --- a/src/mantle/lib/TabTools.java +++ /dev/null @@ -1,30 +0,0 @@ -package mantle.lib; - -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public class TabTools extends CreativeTabs -{ - ItemStack display; - - public TabTools(String label) - { - super(label); - } - - public void init (ItemStack stack) - { - display = stack; - } - - public ItemStack getIconItemStack () - { - return display; - } - - public Item getTabIconItem () - { - return display.getItem(); - } -} \ No newline at end of file diff --git a/src/mantle/lib/client/MantleClientRegistry.java b/src/mantle/lib/client/MantleClientRegistry.java deleted file mode 100644 index f4423c7..0000000 --- a/src/mantle/lib/client/MantleClientRegistry.java +++ /dev/null @@ -1,67 +0,0 @@ -package mantle.lib.client; - -import java.util.HashMap; -import java.util.Map; - -import com.google.common.collect.Maps; - -import mantle.books.client.BookImage; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; - -public class MantleClientRegistry -{ - public static Map manualIcons = Maps.newHashMap(); - public static Map recipeIcons = Maps.newHashMap(); - public static HashMap imageCache = Maps.newHashMap(); - - public static ItemStack defaultStack = new ItemStack(Items.iron_ingot); - - public static BookImage getBookImageFromCache (String s) - { - return imageCache.get(s); - } - - public static void registerManualIcon (String name, ItemStack stack) - { - manualIcons.put(name, stack); - } - - public static ItemStack getManualIcon (String textContent) - { - ItemStack stack = manualIcons.get(textContent); - if (stack != null) - return stack; - return defaultStack; - } - - public static void registerManualSmallRecipe (String name, ItemStack output, ItemStack... stacks) - { - ItemStack[] recipe = new ItemStack[5]; - recipe[0] = output; - System.arraycopy(stacks, 0, recipe, 1, 4); - recipeIcons.put(name, recipe); - } - - public static void registerManualLargeRecipe (String name, ItemStack output, ItemStack... stacks) - { - ItemStack[] recipe = new ItemStack[10]; - recipe[0] = output; - System.arraycopy(stacks, 0, recipe, 1, 9); - recipeIcons.put(name, recipe); - } - - public static void registerManualFurnaceRecipe (String name, ItemStack output, ItemStack input) - { - ItemStack[] recipe = new ItemStack[2]; - recipe[0] = output; - recipe[1] = input; - recipeIcons.put(name, recipe); - } - - public static ItemStack[] getRecipeIcons (String recipeName) - { - return recipeIcons.get(recipeName); - } - -} diff --git a/src/mantle/lib/environment/EnvironmentChecks.java b/src/mantle/lib/environment/EnvironmentChecks.java deleted file mode 100644 index 53738d6..0000000 --- a/src/mantle/lib/environment/EnvironmentChecks.java +++ /dev/null @@ -1,79 +0,0 @@ -package mantle.lib.environment; - -import static mantle.lib.CoreRepo.logger; -import static mantle.lib.CoreRepo.modId; - -import java.util.ArrayList; -import java.util.List; - -import mantle.crash.CallableSuppConfig; -import mantle.crash.CallableUnsuppConfig; -import mantle.lib.CoreConfig; -import cpw.mods.fml.client.FMLClientHandler; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.ICrashCallable; -import cpw.mods.fml.common.Loader; -import cpw.mods.fml.relauncher.Side; - -/** - * Environment Checks - * - * Checks the runtime environment is safe for use. If not, registers warnings and adds a suitable crash callable. - * - * @author Sunstrike - */ -public class EnvironmentChecks -{ - - private EnvironmentChecks() - { - } // Singleton - - // Usable by other mods to detect Optifine. - public static boolean hasOptifine = false; - - /** - * Checks for conflicting stuff in environment; adds callable to any crash logs if so. - * Note: This code adds additional data to crashlogs. It does not trigger any crashes. - */ - @SuppressWarnings("rawtypes") - public static void verifyEnvironmentSanity () - { - List modIds = new ArrayList(); - - if (FMLCommonHandler.instance().getSide() == Side.CLIENT && FMLClientHandler.instance().hasOptifine() || Loader.isModLoaded("optifine")) - { - if (!CoreConfig.silenceEnvChecks) - logger.error("[Environment Checks] Optifine detected. This may cause issues due to base edits or ASM usage."); - hasOptifine = true; - modIds.add("optifine"); - } - - try - { - Class cl = Class.forName("org.bukkit.Bukkit"); - if (cl != null) - { - if (!CoreConfig.silenceEnvChecks) - logger.error("[Environment Checks] Bukkit implementation detected. This may cause issues. Bukkit implementations include Craftbukkit and Cauldron(MCPC+)."); - modIds.add("bukkit"); - } - } - catch (Exception ex) - { - // No Bukkit in environment. - } - - if (modIds.size() == 0) - { - ICrashCallable callable = new CallableSuppConfig(modId); - FMLCommonHandler.instance().registerCrashCallable(callable); - } - else - { - ICrashCallable callable = new CallableUnsuppConfig(modId, modIds); - FMLCommonHandler.instance().registerCrashCallable(callable); - } - } - -} diff --git a/src/mantle/math/Dozenal.java b/src/mantle/math/Dozenal.java deleted file mode 100644 index 482e375..0000000 --- a/src/mantle/math/Dozenal.java +++ /dev/null @@ -1,85 +0,0 @@ -package mantle.math; - -/** - * Dozenal Converter - * - * Converts decimals into dozenal. - * - * @author mDiyo - */ - -import java.util.LinkedList; - -public class Dozenal -{ - - @SuppressWarnings("unused") - public static String convertToDozenal (byte i) - { - return convertDecimal(i); - } - - @SuppressWarnings("unused") - public static String convertToDozenal (short i) - { - return convertDecimal(i); - } - - @SuppressWarnings("unused") - public static String convertToDozenal (int i) - { - return convertDecimal(i); - } - - public static String convertDecimal (int i) - { - int num = i; - LinkedList list = new LinkedList(); - while (num > 0) - { - list.add(getDozenalCharacter(num % 12)); - num /= 12; - } - StringBuilder builder = new StringBuilder(); - for (int iter = list.size() - 1; iter > 0; iter--) - { - builder.append(list.get(iter)); - } - return builder.toString(); - } - - public static char getDozenalCharacter (int i) - { - assert i < 12 : "Base 10 number should be less than 12"; - - switch (i) - { - case 0: - return '0'; //Zero - case 1: - return '1'; //One - case 2: - return '2'; //Two - case 3: - return '3'; //Three - case 4: - return '4'; //Four - case 5: - return '5'; //Five - case 6: - return '6'; //Six - case 7: - return '7'; //Seven - case 8: - return '8'; //Eight - case 9: - return '9'; //Nine - case 10: - return 'X'; //Dec - case 11: - return 'E'; //El - } - - return 'Q'; - } -} \ No newline at end of file diff --git a/src/mantle/module/ILoadableModule.java b/src/mantle/module/ILoadableModule.java deleted file mode 100644 index 94e0032..0000000 --- a/src/mantle/module/ILoadableModule.java +++ /dev/null @@ -1,26 +0,0 @@ -package mantle.module; - -/** - * Interface for modules for dealing with other mods. - * - * Note that all ILoadableModule's should have a static String field "modId" which contains the mod ID of the mod it supports. - * This is accessed by reflection because Java is dumb and has no statics in interfaces. - * - * @author Arkan - */ -@Deprecated //See Pulsar package for replacement -public interface ILoadableModule { - - // Example modId field - //public static String modId = "ExampleMod"; - - // Called during PreInit - public abstract void preInit(); - - // Called during Init - public abstract void init(); - - // Called during PostInit - public abstract void postInit(); - -} \ No newline at end of file diff --git a/src/mantle/module/ModuleController.java b/src/mantle/module/ModuleController.java deleted file mode 100644 index a387b19..0000000 --- a/src/mantle/module/ModuleController.java +++ /dev/null @@ -1,180 +0,0 @@ -package mantle.module; - -import cpw.mods.fml.common.Loader; -import net.minecraftforge.common.config.Configuration; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.File; -import java.util.ArrayList; - -/** - * Controller for mod compat modules. - * - * @author Sunstrike - * @author Arkan Emberwalker - */ -@Deprecated //See PulseManager for replacement -public class ModuleController { - - private enum State { - WAITING, PREINIT, INIT, POSTINIT, DONE - } - - private ArrayList modules = new ArrayList(); - private State currentState = State.WAITING; - private Logger logger; - private Configuration config; - - /** - * Constructor for a config-less plugin loader - * - * @param modName The human-readable name of the invoking mod. Used for logger construction. - */ - @SuppressWarnings("unused") - public ModuleController(String modName) { - this.logger = LogManager.getLogger(modName + "-ModuleController"); - this.config = null; - } - - /** - * Constructor for a config-using plugin loader - * - * @param confName The name for the configuration file (should end in .cfg) - * @param modName The human-readable name of the invoking mod. Used for logger construction. - */ - public ModuleController(String confName, String modName) { - this.logger = LogManager.getLogger(modName + "-ModuleController"); - this.config = new Configuration(new File(Loader.instance().getConfigDir().toString() + File.separator + confName)); - } - - /** - * The host mod should invoke this when it receives the FML PreInitialization event. - */ - public void preInit() { - currentState = State.PREINIT; - for (ILoadableModule m : modules) m.preInit(); - } - - /** - * The host mod should invoke this when it receives the FML Initialization event. - */ - public void init() { - currentState = State.INIT; - for (ILoadableModule m : modules) m.init(); - } - - /** - * The host mod should invoke this when it receives the FML PostInitialization event. - */ - public void postInit() { - currentState = State.POSTINIT; - for (ILoadableModule m : modules) m.postInit(); - currentState = State.DONE; - } - - /** - * Main registration point for modules. - * - * This version will always check the configuration, if one is defined, before attempting to load a plugin. This is - * the preferred entry point. To bypass the config test, use registerUncheckedModule(). - * - * @param mod The module to attempt to register. - * @return True on success, false on error or rejection. - */ - @SuppressWarnings("unused") - public boolean registerModule(Class mod) { - String mID = getModId(mod); - if (mID == null) return false; - - boolean allowedByConf = true; - if (config != null) { - config.load(); - allowedByConf = config.get("Modules", mID, true).getBoolean(true); - config.save(); - } - - if (!allowedByConf || !Loader.isModLoaded(mID)) return false; - - return doSetup(mod, mID); - } - - /** - * Unchecked handler for registering a module forcefully. - * - * This version bypasses any config test; use registerModule where possible. This is only intended for modules - * the user is not allowed to configure (e.g. Mystcraft blacklist plugins). - * - * @param mod The module to attempt to register. - * @return True on success, false on error. - */ - @SuppressWarnings("unused") - public boolean registerUncheckedModule(Class mod) { - String mID = getModId(mod); - if (mID == null || !Loader.isModLoaded(mID)) return false; - - return doSetup(mod, mID); - } - - private String getModId(Class mod) { - String mID; - try { - mID = (String)mod.getField("modId").get(null); - } catch (Exception e) { - logger.error("Module loading failed for class " + mod + "; modId field may be missing."); - return null; - } catch (NoClassDefFoundError ncdf) { // NOTE: Catching Errors is usually bad practice, but we need to here. - logger.error("Module loading failed for class " + mod + "; a referenced class is missing."); - return null; - } - return mID; - } - - /** - * Internal handler which actually does the heavy lifting with loading. - * - * @param mod Module class to setup - * @return True on success, else false. - */ - private boolean doSetup(Class mod, String mID) { - ILoadableModule module; - try { - module = mod.newInstance(); - modules.add(module); - } catch (Exception e) { - logger.error("Could not construct module for " + mID); - logger.error(e.getMessage()); - logger.error(e.getStackTrace()); - return false; - } - - logger.info("Module for " + mID + " loaded successfully."); - - boolean caughtUp = false; - switch (currentState) { - case DONE: - case POSTINIT: - module.preInit(); - module.init(); - module.postInit(); - caughtUp = true; - break; - case INIT: - module.preInit(); - module.init(); - caughtUp = true; - break; - case PREINIT: - module.preInit(); - caughtUp = true; - break; - default: - break; - } - - if (caughtUp) logger.info("Completed catch-up for " + mID + " module."); - - return true; - } - -} \ No newline at end of file diff --git a/src/mantle/player/PlayerUtils.java b/src/mantle/player/PlayerUtils.java deleted file mode 100644 index 5c00465..0000000 --- a/src/mantle/player/PlayerUtils.java +++ /dev/null @@ -1,23 +0,0 @@ -package mantle.player; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ChatComponentText; - -/** - * Misc utils for dealing with players. - * - * @author progwml6 - */ -public class PlayerUtils -{ - - /** - * Sends a given message to a specific player (due to 1.7 axing addChatMessage()) - */ - public static void sendChatMessage (EntityPlayer p, String message) - { - if (p != null && message != null && !message.isEmpty()) - p.addChatComponentMessage(new ChatComponentText(message)); - } - -} diff --git a/src/mantle/pulsar/config/ForgeCFG.java b/src/mantle/pulsar/config/ForgeCFG.java deleted file mode 100644 index ac3f5a1..0000000 --- a/src/mantle/pulsar/config/ForgeCFG.java +++ /dev/null @@ -1,49 +0,0 @@ -package mantle.pulsar.config; - -import cpw.mods.fml.common.Loader; -import mantle.pulsar.pulse.PulseMeta; -import net.minecraftforge.common.config.Configuration; - -import java.io.*; - -/** - * Mantle specific pulsar addon class to support using the forge CFG format for configurations - * @author progwml6 - */ -public class ForgeCFG implements IConfiguration{ - - private static Configuration config; - private final String confPath; - private final String description; - - /** - * Creates a new Configuration object. - * - * Do NOT make this the same as the overall mod configuration; it will clobber it! - * - * @param confName The config file name (without path or .cfg suffix) - * @param description The description for the group that the config entries will be placed in. - */ - public ForgeCFG(String confName, String description) { - this.confPath = Loader.instance().getConfigDir().toString() + File.separator + confName + ".cfg"; - this.description = description; - } - - @Override - public void load() { - config = new Configuration(new File(confPath)); - config.load(); - } - - @Override - public boolean isModuleEnabled(PulseMeta meta) { - return config.get(description, meta.getId(), meta.isEnabled(), meta.getDescription()).getBoolean(meta.isEnabled()); - } - - @Override - public void flush() { - if(config.hasChanged()) - config.save(); - } - -} diff --git a/src/mantle/pulsar/control/PulseManager.java b/src/mantle/pulsar/control/PulseManager.java deleted file mode 100644 index 6f1fa67..0000000 --- a/src/mantle/pulsar/control/PulseManager.java +++ /dev/null @@ -1,266 +0,0 @@ -package mantle.pulsar.control; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; - -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.Loader; -import cpw.mods.fml.common.event.FMLInitializationEvent; -import cpw.mods.fml.common.event.FMLPostInitializationEvent; -import cpw.mods.fml.common.event.FMLPreInitializationEvent; -import mantle.pulsar.config.IConfiguration; -import mantle.pulsar.internal.Configuration; -import mantle.pulsar.pulse.PulseMeta; -import mantle.pulsar.internal.logging.ILogger; -import mantle.pulsar.internal.logging.LogManager; -import mantle.pulsar.pulse.Handler; -import mantle.pulsar.pulse.IPulse; -import mantle.pulsar.pulse.Pulse; -import mantle.pulsar.pulse.PulseProxy; - -/** - * Manager class for a given mods Pulses. - * - * Each Pulsar-enabled mod should create one and only one of these to manage its Pulses. - * - * @author Arkan - */ -@SuppressWarnings({"unused", "deprecated"}) -public class PulseManager { - - private final ILogger log; - private final boolean useConfig; - - private final LinkedHashMap pulses = new LinkedHashMap(); - - private boolean blockNewRegistrations = false; - private boolean configLoaded = false; - private IConfiguration conf; - - /** - * Configuration-less constructor. - * - * PulseManagers created this way ignore configurability on child Pulses. This is not recommended. - * - * @param modId The parents ModID. - */ - @Deprecated - public PulseManager(String modId) { - log = LogManager.getLogger("PulseManager-" + modId); - useConfig = false; - conf = null; - } - - /** - * Configuration-using constructor. - * - * This form creates a PulseManager that supports configuration of Pulses by file. Recommended approach. - * - * @param modId The parents ModID. - * @param configName The config file name. - */ - public PulseManager(String modId, String configName) { - log = LogManager.getLogger("PulseManager-" + modId); - useConfig = true; - conf = new Configuration(configName, log); - } - - /** - * Custom configuration-using constructor. - * - * Don't like JSON? Heathen. Lets you handle configuration, to whatever media you like - File, database, death star. - * Whatever really. See {@link mantle.pulsar.config.IConfiguration}. - * - * @param modId The parents ModID. - * @param config Configuration handler. - */ - public PulseManager(String modId, IConfiguration config) { - log = LogManager.getLogger("PulseManager-" + modId); - useConfig = true; - conf = config; - } - - /** - * Register a new Pulse with the manager. - * - * This CANNOT be done after preInit() has been invoked. - * - * @param pulse The Pulse to register. - */ - public void registerPulse(Object pulse) { - if (blockNewRegistrations) throw new RuntimeException("A mod tried to register a plugin after preinit! Pulse: " - + pulse); - if (!configLoaded) { - conf.load(); - configLoaded = true; - } - - String id, description, deps; - boolean forced, enabled, missingDeps = false; - - try { - Pulse p = pulse.getClass().getAnnotation(Pulse.class); - id = p.id(); - description = p.description(); - deps = p.modsRequired(); - forced = p.forced(); - enabled = p.defaultEnable(); - } catch (NullPointerException ex) { - throw new RuntimeException("Could not parse @Pulse annotation for Pulse: " + pulse); - } - - // Work around Java not allowing default-null fields. - if (description.equals("")) description = null; - - if (!deps.equals("")) { - String[] parsedDeps = deps.split(";"); - for (String s : parsedDeps) { - if (!Loader.isModLoaded(s)) { - log.info("Skipping Pulse " + id + "; missing dependency: " + s); - missingDeps = true; - enabled = false; - break; - } - } - } - - PulseMeta meta = new PulseMeta(id, description, forced, enabled); - meta.setEnabled(!missingDeps && getEnabledFromConfig(meta)); - - if (meta.isEnabled()) { - parseAndAddProxies(pulse); - pulses.put(pulse, meta); - } - } - - private boolean getEnabledFromConfig(PulseMeta meta) { - if (meta.isForced() || !useConfig) return true; // Forced or no config set. - - return conf.isModuleEnabled(meta); - } - - /** - * @deprecated FML handles proxies now. - * - * @param pulse Pulse to parse for proxy annotations. - */ - @Deprecated - private void parseAndAddProxies(Object pulse) { - try { - for (Field f : pulse.getClass().getDeclaredFields()) { - log.debug("Parsing field: " + f); - PulseProxy p = f.getAnnotation(PulseProxy.class); - if (p != null) { // Support for deprecated PulseProxy annotation - log.warn("Pulse " + pulse + " used the deprecated PulseProxy annotation. As of Pulsar 0.1.0, it's now preferred to use FML's SidedProxy annotation."); - log.warn("The old PulseProxy parsing will be removed in the next breaking update (Pulsar 1.x)."); - setProxyField(pulse, f, p.clientSide(), p.serverSide()); - } - } - } catch (Exception ex) { - throw new RuntimeException("Pulse annotation parsing failed for Pulse " + pulse + "; " + ex); - } - } - - @Deprecated - private void setProxyField(Object pulse, Field f, String client, String server) throws Exception { - boolean accessible = f.isAccessible(); - f.setAccessible(true); - switch (FMLCommonHandler.instance().getSide()) { - case CLIENT: - f.set(pulse, Class.forName(client).newInstance()); - break; - default: - f.set(pulse, Class.forName(server).newInstance()); - } - f.setAccessible(accessible); - } - - public void preInit(FMLPreInitializationEvent evt) { - if (!blockNewRegistrations) conf.flush(); // First preInit call, so flush config - blockNewRegistrations = true; - - for (Map.Entry e : pulses.entrySet()) { - if(hasRequiredPulses(e)) { - log.debug("Preinitialising Pulse " + e.getValue().getId() + "..."); - if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling - IPulse ip = (IPulse)e.getKey(); - ip.preInit(evt); - } else findAndInvokeHandlers(e.getKey(), evt); - } - } - } - - public void init(FMLInitializationEvent evt) { - for (Map.Entry e : pulses.entrySet()) { - log.debug("Initialising Pulse " + e.getValue().getId() + "..."); - - if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling - IPulse ip = (IPulse)e.getKey(); - ip.init(evt); - log.warn("Pulse " + e.getValue().getId() + " is using the deprecated IPulse interface."); - log.warn("This will be removed in the next major version (Pulsar 1.x) - Please switch to @Handler!"); - } else findAndInvokeHandlers(e.getKey(), evt); - } - } - - public void postInit(FMLPostInitializationEvent evt) { - for (Map.Entry e : pulses.entrySet()) { - log.debug("Postinitialising Pulse " + e.getValue().getId() + "..."); - - if (e.getKey() instanceof IPulse) { // Deprecated IPulse handling - IPulse ip = (IPulse)e.getKey(); - ip.postInit(evt); - } else findAndInvokeHandlers(e.getKey(), evt); - } - } - - /** - * Parse an object for a matching handler for the given object. - * - * @param pulse Object to inspect for Handlers - * @param evt The event object - */ - @SuppressWarnings("unchecked") - private void findAndInvokeHandlers(Object pulse, Object evt) { - for (Method m : pulse.getClass().getDeclaredMethods()) { - try { - if (m.getAnnotation(Handler.class) == null) continue; // Ignore non-@Handler methods - - Class[] pTypes = m.getParameterTypes(); - if (pTypes.length != 1) continue; - - Class pt = pTypes[0]; - if (pt.isAssignableFrom(evt.getClass())) { - m.invoke(pulse, evt); - } - } catch (Exception ex) { - log.warn("Caught exception in findAndInvokeHandlers: " + ex); - ex.printStackTrace(); - } - } - } - - private boolean hasRequiredPulses(Map.Entry entry) { - String deps = entry.getKey().getClass().getAnnotation(Pulse.class).pulsesRequired(); - if (!deps.equals("")) { - String[] parsedDeps = deps.split(";"); - for (String s : parsedDeps) { - if (!isPulseLoaded(s)) { - log.info("Skipping Pulse " + entry.getValue().getId() + "; missing pulse: " + s); - return false; - } - } - } - return true; - } - - public boolean isPulseLoaded(String pulseId) { - for(Map.Entry entry : pulses.entrySet()) { - if(entry.getValue().getId().equals(pulseId)) { - return true; - } - } - return false; - } -} diff --git a/src/mantle/pulsar/internal/logging/ILogger.java b/src/mantle/pulsar/internal/logging/ILogger.java deleted file mode 100644 index 2d26787..0000000 --- a/src/mantle/pulsar/internal/logging/ILogger.java +++ /dev/null @@ -1,23 +0,0 @@ -package mantle.pulsar.internal.logging; - -/** - * Interface for log wrappers. - * - * @author Arkan - */ -@SuppressWarnings("unused") -public interface ILogger { - - public void fatal(String msg); - - public void severe(String msg); - - public void warn(String msg); - - public void info(String msg); - - public void debug(String msg); - - public void trace(String msg); - -} diff --git a/src/mantle/pulsar/internal/logging/JULLogger.java b/src/mantle/pulsar/internal/logging/JULLogger.java deleted file mode 100644 index 13cbd43..0000000 --- a/src/mantle/pulsar/internal/logging/JULLogger.java +++ /dev/null @@ -1,48 +0,0 @@ -package mantle.pulsar.internal.logging; - -import java.util.logging.Logger; - -/** - * Java logger wrapper. - * - * @author Arkan - */ -public class JULLogger implements ILogger { - - private final Logger log; - - public JULLogger(String name) { - log = Logger.getLogger(name); - } - - @Override - public void fatal(String msg) { - log.severe(msg); // JUL doesn't -have- fatal... - } - - @Override - public void severe(String msg) { - log.severe(msg); - } - - @Override - public void warn(String msg) { - log.warning(msg); - } - - @Override - public void info(String msg) { - log.info(msg); - } - - @Override - public void debug(String msg) { - log.fine(msg); // Good enough. - } - - @Override - public void trace(String msg) { - log.finest(msg); // Closest we'll get. - } - -} diff --git a/src/mantle/pulsar/internal/logging/Log4jLogger.java b/src/mantle/pulsar/internal/logging/Log4jLogger.java deleted file mode 100644 index 9f38239..0000000 --- a/src/mantle/pulsar/internal/logging/Log4jLogger.java +++ /dev/null @@ -1,48 +0,0 @@ -package mantle.pulsar.internal.logging; - -import org.apache.logging.log4j.Logger; - -/** - * Log4j log wrapper. - * - * @author Arkan - */ -public class Log4jLogger implements ILogger { - - private final Logger log; - - public Log4jLogger(String name) { - log = org.apache.logging.log4j.LogManager.getLogger(name); - } - - @Override - public void fatal(String msg) { - log.fatal(msg); - } - - @Override - public void severe(String msg) { - log.error(msg); - } - - @Override - public void warn(String msg) { - log.warn(msg); - } - - @Override - public void info(String msg) { - log.info(msg); - } - - @Override - public void debug(String msg) { - log.debug(msg); - } - - @Override - public void trace(String msg) { - log.trace(msg); - } - -} diff --git a/src/mantle/pulsar/internal/logging/LogManager.java b/src/mantle/pulsar/internal/logging/LogManager.java deleted file mode 100644 index b727ebf..0000000 --- a/src/mantle/pulsar/internal/logging/LogManager.java +++ /dev/null @@ -1,39 +0,0 @@ -package mantle.pulsar.internal.logging; - -/** - * Static class for getting generic loggers. - * - * @author Arkan - */ -public class LogManager { - - private LogManager() {} // Singleton. - - private static final boolean useLog4j2; - - /* - * Detect the presence of log4j2. - * - * If it's present, we can assume we should be using the damn thing. - */ - static { - boolean l4j = false; - try { - Class cl = Class.forName("org.apache.logging.log4j.LogManager"); - if (cl == null) throw new ClassNotFoundException("This should never happen..."); - l4j = true; - } catch (ClassNotFoundException cnfe) { - // Ignore - } - useLog4j2 = l4j; - } - - public static ILogger getLogger(String name) { - if (useLog4j2) { - return new Log4jLogger(name); - } else { - return new JULLogger(name); - } - } - -} diff --git a/src/mantle/pulsar/pulse/Handler.java b/src/mantle/pulsar/pulse/Handler.java deleted file mode 100644 index 547648d..0000000 --- a/src/mantle/pulsar/pulse/Handler.java +++ /dev/null @@ -1,14 +0,0 @@ -package mantle.pulsar.pulse; - -import java.lang.annotation.*; - -/** - * Annotates methods to be used for event handling. - * - * @author Arkan - */ -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -public @interface Handler -{} diff --git a/src/mantle/pulsar/pulse/IPulse.java b/src/mantle/pulsar/pulse/IPulse.java deleted file mode 100644 index cb4febd..0000000 --- a/src/mantle/pulsar/pulse/IPulse.java +++ /dev/null @@ -1,38 +0,0 @@ -package mantle.pulsar.pulse; - -import cpw.mods.fml.common.event.FMLInitializationEvent; -import cpw.mods.fml.common.event.FMLPostInitializationEvent; -import cpw.mods.fml.common.event.FMLPreInitializationEvent; - -/** - * Base interface for all Pulsar modules ("pulses"). - * - * @deprecated Use the new {@link Handler} annotation. - * - * @author Arkan - */ -@Deprecated -public interface IPulse { - - /** - * FML preinit from the parent mod. - * - * @param evt The FML event inherited from this Pulses parent. - */ - public void preInit(FMLPreInitializationEvent evt); - - /** - * FML init from the parent mod. - * - * @param evt The FML event inherited from this Pulses parent. - */ - public void init(FMLInitializationEvent evt); - - /** - * FML postinit from the parent mod. - * - * @param evt The FML event inherited from this Pulses parent. - */ - public void postInit(FMLPostInitializationEvent evt); - -} diff --git a/src/mantle/pulsar/pulse/PulseMeta.java b/src/mantle/pulsar/pulse/PulseMeta.java deleted file mode 100644 index a493638..0000000 --- a/src/mantle/pulsar/pulse/PulseMeta.java +++ /dev/null @@ -1,39 +0,0 @@ -package mantle.pulsar.pulse; - -/** - * Metadata wrapper for parsed @Pulse metadata. - * - * @author Arkan - */ -public class PulseMeta { - - private String id, description; - private boolean forced, enabled; - - public PulseMeta(String id, String description, boolean forced, boolean enabled) { - this.id = id; - this.description = description; - this.forced = forced; - this.enabled = enabled; - } - - public String getId() { - return id; - } - - public String getDescription() { - return description; - } - - public boolean isForced() { - return forced; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } -} diff --git a/src/mantle/pulsar/pulse/PulseProxy.java b/src/mantle/pulsar/pulse/PulseProxy.java deleted file mode 100644 index b8089bb..0000000 --- a/src/mantle/pulsar/pulse/PulseProxy.java +++ /dev/null @@ -1,28 +0,0 @@ -package mantle.pulsar.pulse; - -import java.lang.annotation.*; - -/** - * Annotation to denote a field that should be populated by a side-specific proxy. - * - * @deprecated Use FML's @SidedProxy instead. - * - * @author Arkan - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -@Documented -@Deprecated -public @interface PulseProxy { - - /** - * @return The FQCN of the client proxy. - */ - public String clientSide(); - - /** - * @return The FQCN of the server proxy. - */ - public String serverSide(); - -} diff --git a/src/mantle/utils/CraftingHandler.java b/src/mantle/utils/CraftingHandler.java deleted file mode 100644 index 4cdc8fe..0000000 --- a/src/mantle/utils/CraftingHandler.java +++ /dev/null @@ -1,329 +0,0 @@ -package mantle.utils; - -import static mantle.lib.CoreRepo.logger; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import cpw.mods.fml.common.registry.GameRegistry; -import mantle.lib.CoreConfig; -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.CraftingManager; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.item.crafting.ShapedRecipes; -import net.minecraft.item.crafting.ShapelessRecipes; -import net.minecraftforge.oredict.OreDictionary; -import net.minecraftforge.oredict.ShapedOreRecipe; -import net.minecraftforge.oredict.ShapelessOreRecipe; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class CraftingHandler { - private static boolean ia1NG; - - public static void logConflicts () { - - //GameRegistry.addShapelessRecipe(new ItemStack(Items.diamond_hoe), Blocks.planks, Items.stick, Items.chainmail_boots); - //GameRegistry.addShapelessRecipe(new ItemStack(Items.apple), Blocks.planks, Items.stick, Items.chainmail_boots); - if (CoreConfig.dumpRecipeConflicts) { - for (Map.Entry> me : getPotentialConflicts().entrySet()) { - String s = ""; - for (IRecipe i : me.getValue()) { - s += print(i); - } - logger.error("found conflict: \n" + s); - } - } - } - - public static Map> getPotentialConflicts () { - logger.info("dumping recipe conflicts to log this can take a while"); - Map> conflicts = Maps.newHashMap(); - CraftingManager inst = CraftingManager.getInstance(); - List recipes = inst.getRecipeList(); - for (IRecipe i : recipes) { - for (int r = 0; r < recipes.size(); r++) { - IRecipe rc = recipes.get(r); - if (i != null && rc != null) { - boolean comp = compare(i, rc); - if (comp && !areItemStacksEqual(i.getRecipeOutput(), rc.getRecipeOutput())) { - if (conflicts.containsKey(i)) { - List l = conflicts.get(i); - conflicts.remove(i); - if (!l.contains(r)) { - l.add(recipes.get(r)); - } - conflicts.put(i, l); - } else if (conflicts.containsKey(rc)) { - List l = conflicts.get(rc); - conflicts.remove(rc); - if (!l.contains(i)) { - l.add(i); - } - conflicts.put(rc, l); - } else { - List l = Lists.newArrayList(i, rc); - conflicts.put(i, l); - } - if (ia1NG) { - ia1NG = false; - break; - } - } - } - } - } - return conflicts; - } - - private static boolean compare (IRecipe i1, IRecipe i2) { - if (areItemStacksEqual(i1.getRecipeOutput(), i2.getRecipeOutput())) { - return false; - } - boolean is1l = false; - boolean is2l = false; - List il1 = Lists.newArrayList(); - List il2 = Lists.newArrayList(); - ItemStack[] ia1 = null; - boolean invalid = false; - ItemStack[] ia2 = null; - if (i1 instanceof ShapedRecipes) { - ia1 = ((ShapedRecipes) i1).recipeItems.clone(); - } else if (i1 instanceof ShapelessRecipes) { - il1 = new ArrayList(((ShapelessRecipes) i1).recipeItems); - //logger.error("SL Recipe: \n" + print(i1)); - is1l = true; - } else if (i1 instanceof ShapedOreRecipe) { - Object[] o = ((ShapedOreRecipe) i1).getInput(); - ia1 = new ItemStack[o.length]; - for (int in = 0; in < o.length; in++) { - if (o[in] != null && o[in] instanceof ItemStack) { - ia1[in] = (ItemStack) o[in]; - } else if (o[in] != null) { - ia1[in] = ((ArrayList) o[in]).get(0); - } else { - ia1[in] = null; - } - } - } else if (i1 instanceof ShapelessOreRecipe) { - il1 = new ArrayList(); - for (Object o : ((ShapelessOreRecipe) i1).getInput()) { - if (o != null && o instanceof ItemStack) { - ItemStack is = (ItemStack) o; - il1.add(is); - } else if (o != null) { - ItemStack is = ((ArrayList) o).get(0); - il1.add(is); - } else { - il1.add(null); - } - } - is1l = true; - } else { - ia1NG = true; - invalid = true; - } - if (i2 instanceof ShapedRecipes) { - ia2 = ((ShapedRecipes) i2).recipeItems.clone(); - } else if (i2 instanceof ShapelessRecipes) { - il2 = new ArrayList(((ShapelessRecipes) i2).recipeItems); - is2l = true; - } else if (i2 instanceof ShapedOreRecipe) { - Object[] o = ((ShapedOreRecipe) i2).getInput(); - ia2 = new ItemStack[o.length]; - for (int in = 0; in < o.length; in++) { - if (o.length == 6) { - print(i2); - } - if (o[in] != null && o[in] instanceof ItemStack) { - ia2[in] = (ItemStack) o[in]; - } else if (o[in] != null) { - ItemStack is = ((ArrayList) o[in]).get(0); - ia2[in] = is; - } else { - ia2[in] = null; - } - } - } else if (i2 instanceof ShapelessOreRecipe) { - il2 = new ArrayList(); - for (Object o : ((ShapelessOreRecipe) i2).getInput()) { - if (o != null && o instanceof ItemStack) { - ItemStack is = (ItemStack) o; - il2.add(is); - } else if (o != null) { - ItemStack is = ((ArrayList) o).get(0); - il2.add(is); - } else { - il2.add(null); - } - } - is2l = true; - } else { - invalid = true; - } - if (!invalid) { - if (!is1l && !is2l) { - if (ia1 == null) { - logger.error("ia1 null"); - } - if (ia2 == null) { - logger.error("ia2 null"); - } - if (ia1.length != ia2.length) { - return false; - } - for (int i = 0; i < ia1.length; i++) { - if (ia1[i] != null && ia2[i] != null) { - if (!areItemStacksEqual(ia1[i], ia2[i])) { - return false; - } - } else { - return false; - } - } - } else if (is1l && is2l) { - if (il1.size() == il2.size()) { - boolean has = false; - for (int i = 0; i < il1.size(); i++) { - ItemStack ti1 = il1.get(i); - for (int j = 0; j < il2.size(); j++) { - if (areItemStacksEqual(ti1, il2.get(j))) { - il2.remove(j); - has = true; - break; - } - } - } - if (!has) { - return false; - } - if (il2.size() != 0) { - return false; - } - } else { - return false; - } - } else { - List stacks = is1l ? il1 : il2; - ItemStack[] stcks = is2l ? ia1 : ia2; - for (ItemStack i : stcks) { - if (!stacks.contains(i)) { - return false; - } else { - stacks.remove(i); - } - } - } - } else { - return false; - } - if (i1 instanceof ShapedOreRecipe && i2 instanceof ShapedOreRecipe) { - int i1w, i2w, i1h, i2h; - try { - Class cl = ShapedOreRecipe.class; - Field w = cl.getDeclaredField("width"); - w.setAccessible(true); - Field h = cl.getDeclaredField("height"); - h.setAccessible(true); - i1w = (Integer) w.get((ShapedOreRecipe) i1); - i2w = (Integer) w.get((ShapedOreRecipe) i2); - i1h = (Integer) h.get((ShapedOreRecipe) i1); - i2h = (Integer) h.get((ShapedOreRecipe) i2); - if (i1w != i2w || i1h != i2h) { - return false; - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - //logger.error("CONFLICT SET: \n" + print(i1) + print(i2)); - return true; - } - - private static String print (IRecipe i1) { - String out = ""; - if (i1 instanceof ShapedRecipes) { - out += "SHAPED " + toStr(i1.getRecipeOutput()) + "\n"; - for (ItemStack i : ((ShapedRecipes) i1).recipeItems) { - if (i != null && i.getItem() != null) { - out += toStr((ItemStack) i) + "\n"; - } else { - out += "null \n"; - } - } - - } else if (i1 instanceof ShapelessRecipes) { - out += "SHAPELESS " + toStr(i1.getRecipeOutput()) + "\n"; - for (Object i : ((ShapelessRecipes) i1).recipeItems) { - if ((ItemStack) i != null && ((ItemStack) i).getItem() != null) { - out += toStr((ItemStack) i) + "\n"; - } else { - out += "null \n"; - } - } - } else if (i1 instanceof ShapedOreRecipe) { - out += "SHAPED ORE " + toStr(i1.getRecipeOutput()) + "\n"; - Object[] o = ((ShapedOreRecipe) i1).getInput(); - ItemStack[] ia1 = new ItemStack[o.length]; - for (int in = 0; in < o.length; in++) { - if (o[in] != null && o[in] instanceof ItemStack) { - ia1[in] = (ItemStack) o[in]; - } else if (o[in] != null) { - ia1[in] = ((ArrayList) o[in]).get(0); - } else { - ia1[in] = null; - } - } - - for (Object i : ia1) { - if (i != null && ((ItemStack) i).getItem() != null) { - out += toStr((ItemStack) i) + "\n"; - } else { - out += "null \n"; - } - } - } else if (i1 instanceof ShapelessOreRecipe) { - out += "SHAPELESS ORE " + toStr(i1.getRecipeOutput()) + "\n"; - ItemStack i; - for (Object ob : ((ShapelessOreRecipe) i1).getInput()) { - if (ob instanceof ItemStack) { - i = (ItemStack) ob; - } else { - i = ((ArrayList) ob).get(0); - } - if ((ItemStack) i != null && ((ItemStack) i).getItem() != null) { - out += toStr((ItemStack) i) + "\n"; - } else { - out += "null \n"; - } - } - } - return out; - } - - private static String toStr (ItemStack is) { - return GameRegistry.findUniqueIdentifierFor(((ItemStack) is).getItem()) + " " + ((ItemStack) is).toString(); - } - - public static boolean areItemStacksEqual (ItemStack a, ItemStack b) { - if ((a == null || b == null) && !(a == null && b == null)) { - return false; - } - if ((a == null && b == null)) { - return true; - } - return a.stackSize != b.stackSize - ? false - : (a.getItem() != b.getItem() - ? false - : (compdamage(a, b) - ? false - : (a.stackTagCompound == null && b.stackTagCompound != null ? false : a.stackTagCompound == null || a.stackTagCompound.equals(b.stackTagCompound)))); - } - - public static boolean compdamage (ItemStack a, ItemStack b) { - return a.getCurrentDurability() != b.getCurrentDurability() || a.getCurrentDurability() == OreDictionary.WILDCARD_VALUE || b.getCurrentDurability() == OreDictionary.WILDCARD_VALUE; - } -} \ No newline at end of file diff --git a/src/mantle/utils/ItemMetaWrapper.java b/src/mantle/utils/ItemMetaWrapper.java deleted file mode 100644 index 080d098..0000000 --- a/src/mantle/utils/ItemMetaWrapper.java +++ /dev/null @@ -1,40 +0,0 @@ -package mantle.utils; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public class ItemMetaWrapper { - public final Item item; - public final Integer meta; - - public ItemMetaWrapper(Item item, Integer meta) { - this.item = item; - this.meta = meta; - } - - public ItemMetaWrapper(ItemStack stack) - { - this.item = stack.getItem(); - this.meta = stack.getMetadata(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ItemMetaWrapper itemMeta = (ItemMetaWrapper) o; - - if (item != null ? !(item == itemMeta.item) : itemMeta.item != null) return false; - if (meta != null ? !meta.equals(itemMeta.meta) : itemMeta.meta != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = item != null ? item.hashCode() : 0; - result = 31 * result + (meta != null ? meta.hashCode() : 0); - return result; - } -} diff --git a/src/mantle/utils/ItemStackNBTWrapper.java b/src/mantle/utils/ItemStackNBTWrapper.java deleted file mode 100644 index b29af2a..0000000 --- a/src/mantle/utils/ItemStackNBTWrapper.java +++ /dev/null @@ -1,30 +0,0 @@ -package mantle.utils; - -import net.minecraft.item.ItemStack; - -public class ItemStackNBTWrapper { - public final ItemStack stack; - - public ItemStackNBTWrapper(ItemStack stack) { - this.stack = stack; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ItemStackNBTWrapper that = (ItemStackNBTWrapper) o; - - return ItemStack.areItemStacksEqual(this.stack, that.stack); - } - - @Override - public int hashCode() { - int result = stack.getItem() != null ? stack.getItem().hashCode() : 0; - result = 31 * result + stack.getMetadata(); - result = 31 * result + (stack.getTagCompound() != null ? stack.getTagCompound().hashCode() : 0); - result = 31 * result + stack.stackSize; - return result; - } -} diff --git a/src/mantle/utils/ItemStackWrapper.java b/src/mantle/utils/ItemStackWrapper.java deleted file mode 100644 index 65678e8..0000000 --- a/src/mantle/utils/ItemStackWrapper.java +++ /dev/null @@ -1,38 +0,0 @@ -package mantle.utils; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public class ItemStackWrapper extends ItemMetaWrapper { - public final Integer stacksize; - - public ItemStackWrapper(Item item, Integer meta, Integer stacksize) { - super(item, meta); - this.stacksize = stacksize; - } - - public ItemStackWrapper(ItemStack stack, Integer stacksize) { - super(stack); - this.stacksize = stacksize; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; - - ItemStackWrapper that = (ItemStackWrapper) o; - - if (stacksize != null ? !stacksize.equals(that.stacksize) : that.stacksize != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (stacksize != null ? stacksize.hashCode() : 0); - return result; - } -} diff --git a/src/mantle/world/ChunkCoord.java b/src/mantle/world/ChunkCoord.java deleted file mode 100644 index f629024..0000000 --- a/src/mantle/world/ChunkCoord.java +++ /dev/null @@ -1,94 +0,0 @@ -package mantle.world; - -import java.io.Serializable; - -import mantle.world.CoordTuple; -import net.minecraft.world.chunk.Chunk; - -/** - * Standardized implementation for representing and manipulating Chunk Coordinates. Provides standard Java Collection interaction. - * From COFH LIB(modified to use mantle's coordtuple instead) - * @author King Lemming - * - */ -public final class ChunkCoord implements Comparable, Serializable -{ - - public int chunkX; - public int chunkZ; - - public ChunkCoord(Chunk chunk) - { - - this.chunkX = chunk.xPosition; - this.chunkZ = chunk.zPosition; - } - - public ChunkCoord(CoordTuple c) - { - - this(c.x >> 4, c.z >> 4); - } - - public ChunkCoord(int x, int z) - { - - this.chunkX = x; - this.chunkZ = z; - } - - public int getCenterX () - { - - return (this.chunkX << 4) + 8; - } - - public int getCenterZ () - { - - return (this.chunkZ << 4) + 8; - } - - public ChunkCoord copy () - { - - return new ChunkCoord(chunkX, chunkZ); - } - - @Override - public boolean equals (Object obj) - { - - if (!(obj instanceof ChunkCoord)) - { - return false; - } - ChunkCoord other = (ChunkCoord) obj; - return this.chunkX == other.chunkX && this.chunkZ == other.chunkZ; - } - - @Override - public int hashCode () - { - - int hash = chunkX; - hash *= 31 + this.chunkZ; - return hash; - } - - @Override - public String toString () - { - - return "[" + this.chunkX + ", " + this.chunkZ + "]"; - } - - /* Comparable */ - @Override - public int compareTo (ChunkCoord other) - { - - return this.chunkX == other.chunkX ? this.chunkZ - other.chunkZ : this.chunkX - other.chunkX; - } - -} diff --git a/src/mantle/world/CoordTuple.java b/src/mantle/world/CoordTuple.java deleted file mode 100644 index b09a516..0000000 --- a/src/mantle/world/CoordTuple.java +++ /dev/null @@ -1,175 +0,0 @@ -package mantle.world; - -/** - * CoordTuple - * - * @author mDiyo - */ -@SuppressWarnings("rawtypes") -public class CoordTuple implements Comparable -{ - public final int x; - public final int y; - public final int z; - - public CoordTuple(double posX, double posY, double posZ) - { - x = (int) Math.floor(posX); - y = (int) Math.floor(posY); - z = (int) Math.floor(posZ); - } - - public boolean equalCoords (int posX, int posY, int posZ) - { - if (this.x == posX && this.y == posY && this.z == posZ) - return true; - else - return false; - } - - public boolean equals (Object obj) { - if (!(obj instanceof CoordTuple)) { - return false; - } - - CoordTuple that = (CoordTuple)obj; - return this.x == that.x && this.y == that.y && this.z == that.z; - } - - @Override - public int hashCode () - { - final int prime = 31; - int result = 1; - result = prime * result + x; - result = prime * result + y; - result = prime * result + z; - return result; - } - - public String toString () - { - return "X: " + x + ", Y: " + y + ", Z: " + z; - } - - @Override - public int compareTo (Object o) - { - if (o == null) - throw new NullPointerException("Object cannot be null"); - - CoordTuple coord = (CoordTuple) o; - - if (x < coord.x) - { - return -1; - } - if (x > coord.x) - { - return 1; - } - if (y < coord.y) - { - return -1; - } - if (y > coord.y) - { - return 1; - } - if (z < coord.z) - { - return -1; - } - if (z > coord.z) - { - return 1; - } - - return 0; - } - - public static CoordTuple up (int x, int y, int z) - { - return new CoordTuple(x, y + 1, z); - } - - public static CoordTuple down (int x, int y, int z) - { - return new CoordTuple(x, y - 1, z); - } - - public static CoordTuple north (int x, int y, int z) - { - return new CoordTuple(x, y, z - 1); - } - - public static CoordTuple south (int x, int y, int z) - { - return new CoordTuple(x, y, z + 1); - } - - public static CoordTuple east (int x, int y, int z) - { - return new CoordTuple(x + 1, y, z); - } - - public static CoordTuple west (int x, int y, int z) - { - return new CoordTuple(x - 1, y, z); - } - - public static CoordTuple inFront (int x, int y, int z, int meta) - { - switch (meta) - { - case 0: - return down(x, y, z); - case 1: - return up(x, y, z); - case 2: - return north(x, y, z); - case 3: - return south(x, y, z); - case 4: - return west(x, y, z); - case 5: - return east(x, y, z); - default: - return new CoordTuple(x, y, z); - } - } - - public static CoordTuple behind (int x, int y, int z, int meta) - { - switch (meta) - { - case 1: - return down(x, y, z); - case 0: - return up(x, y, z); - case 3: - return north(x, y, z); - case 2: - return south(x, y, z); - case 5: - return west(x, y, z); - case 4: - return east(x, y, z); - default: - return new CoordTuple(x, y, z); - } - } - - public int getDistanceFrom (CoordTuple tuple) - { - return getDistanceFrom(tuple.x, tuple.y, tuple.z); - } - - public int getDistanceFrom (int x1, int y1, int z1) - { - int xPos = x - x1; - int yPos = y - y1; - int zPos = z - z1; - return xPos * xPos + yPos * yPos + zPos * zPos; - } -} diff --git a/src/mantle/world/CoordTuplePair.java b/src/mantle/world/CoordTuplePair.java deleted file mode 100644 index 67b3547..0000000 --- a/src/mantle/world/CoordTuplePair.java +++ /dev/null @@ -1,24 +0,0 @@ -package mantle.world; - -/** - * CoordTuplePair - * - * @author mDiyo - */ -public class CoordTuplePair -{ - public CoordTuple a; - public CoordTuple b; - - public CoordTuplePair(CoordTuple a, CoordTuple b) - { - this.a = a; - this.b = b; - } - - public CoordTuplePair(int aX, int aY, int aZ, int bX, int bY, int bZ) - { - this.a = new CoordTuple(aX, aY, aZ); - this.b = new CoordTuple(bX, bY, bZ); - } -} \ No newline at end of file diff --git a/src/mantle/world/CoordTupleSort.java b/src/mantle/world/CoordTupleSort.java deleted file mode 100644 index 2ce1aea..0000000 --- a/src/mantle/world/CoordTupleSort.java +++ /dev/null @@ -1,31 +0,0 @@ -package mantle.world; - -import java.util.Comparator; - -/** - * CoordTupleSort - * - * @author mDiyo - */ -@SuppressWarnings("rawtypes") -public class CoordTupleSort implements Comparator -{ - @Override - public int compare (Object o1, Object o2) - { - CoordTuple c1 = (CoordTuple) o1; - CoordTuple c2 = (CoordTuple) o2; - - //Sort by y, then x, then z - if (c1.y != c2.y) - return c1.y - c2.y; - - if (c1.x != c2.x) - return c1.x - c2.x; - - if (c1.z != c2.z) - return c1.z - c2.z; - - return 0; - } -} diff --git a/src/mantle/world/DimensionCoordPair.java b/src/mantle/world/DimensionCoordPair.java deleted file mode 100644 index c186674..0000000 --- a/src/mantle/world/DimensionCoordPair.java +++ /dev/null @@ -1,59 +0,0 @@ -package mantle.world; - -/** - * DimensionCoordPair - * - * @author mDiyo - */ -public class DimensionCoordPair -{ - public final int dim; - public final int x; - public final int z; - - public DimensionCoordPair(int worldID, int posX, int posZ) - { - dim = worldID; - x = posX; - z = posZ; - } - - public boolean equalCoords (int worldID, int posX, int posZ) - { - if (this.dim == posX && this.x == posX && this.z == posZ) - return true; - else - return false; - } - - @Override - public boolean equals (Object obj) - { - if (obj == null) - return false; - - if (getClass() == obj.getClass()) - { - DimensionCoordPair coord = (DimensionCoordPair) obj; - if (this.dim == coord.dim && this.x == coord.x && this.z == coord.z) - return true; - } - return false; - } - - @Override - public int hashCode () - { - final int prime = 37; - int result = 1; - result = prime * result + dim; - result = prime * result + x; - result = prime * result + z; - return result; - } - - public String toString () - { - return "Dim: " + dim + ", X: " + x + ", Z: " + z; - } -} diff --git a/src/mantle/world/DimensionCoordTuple.java b/src/mantle/world/DimensionCoordTuple.java deleted file mode 100644 index f3428f9..0000000 --- a/src/mantle/world/DimensionCoordTuple.java +++ /dev/null @@ -1,62 +0,0 @@ -package mantle.world; - -/** - * DimensionCoordTuple - * - * @author mDiyo - * @author Sunstrike - */ -public class DimensionCoordTuple -{ - public final int dim; - public final int x; - public final int y; - public final int z; - - public DimensionCoordTuple(int worldID, int posX, int posY, int posZ) - { - dim = worldID; - y = posY; - x = posX; - z = posZ; - } - - public boolean equalCoords (int worldID, int posX, int posY, int posZ) - { - if (this.dim == worldID && this.x == posX && this.y == posY && this.z == posZ) - return true; - else - return false; - } - - @Override - public boolean equals (Object obj) - { - if (obj == null) - return false; - - if (getClass() == obj.getClass()) - { - DimensionCoordTuple coord = (DimensionCoordTuple) obj; - return equalCoords(coord.dim, coord.x, coord.y, coord.z); - } - return false; - } - - @Override - public int hashCode () - { - final int prime = 37; - int result = 1; - result = prime * result + dim; - result = prime * result + x; - result = prime * result + y; - result = prime * result + z; - return result; - } - - public String toString () - { - return "Dim: " + dim + ", X: " + x + ", Y: " + y + ", Z: " + z; - } -} diff --git a/src/mantle/world/DirectionUtils.java b/src/mantle/world/DirectionUtils.java deleted file mode 100644 index 7c2d20d..0000000 --- a/src/mantle/world/DirectionUtils.java +++ /dev/null @@ -1,29 +0,0 @@ -package mantle.world; - -import net.minecraftforge.common.util.ForgeDirection; - -/** - * Helper functions for dealing with ForgeDirection - * - * @author Sunstrike - */ -@SuppressWarnings("unused") -public class DirectionUtils -{ - - private DirectionUtils() - { - // No instantiation - } - - public static boolean isRightAngles (ForgeDirection a, ForgeDirection b) - { - return a != b && a != b.getOpposite() && a != ForgeDirection.UNKNOWN && b != ForgeDirection.UNKNOWN; - } - - public static boolean isHorizontal (ForgeDirection a) - { - return a == ForgeDirection.EAST || a == ForgeDirection.NORTH || a == ForgeDirection.SOUTH || a == ForgeDirection.WEST; - } - -} diff --git a/src/mantle/world/WorldHelper.java b/src/mantle/world/WorldHelper.java deleted file mode 100644 index 0b63340..0000000 --- a/src/mantle/world/WorldHelper.java +++ /dev/null @@ -1,31 +0,0 @@ -package mantle.world; - -import mantle.common.ComparisonHelper; -import net.minecraft.init.Blocks; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; - -public class WorldHelper -{ - @Deprecated - public static boolean setBlockToAirBool (World w, int x, int y, int z) - { - return setBlockToAir(w, x, y, z); - } - - public static boolean setBlockToAir (World w, int x, int y, int z) - { - return w.setBlockToAir(x, y, z); - } - - public static boolean isAirBlock (IBlockAccess access, int x, int y, int z) - { - return access.getBlock(x,y,z).isAir(access, x,y,z); - } - - public static boolean isAirBlock (World access, int x, int y, int z) - { - return access.isAirBlock(x,y,z); - } - -}