diff --git a/build.gradle b/build.gradle index be841eb..e182c45 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -//version: 1644349045 +//version: 1656760175 /* DO NOT CHANGE THIS FILE! @@ -9,26 +9,33 @@ Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.g import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar +import org.gradle.internal.logging.text.StyledTextOutput.Style +import org.gradle.internal.logging.text.StyledTextOutputFactory +import java.nio.file.Files +import java.nio.file.Paths import java.util.concurrent.TimeUnit +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream buildscript { repositories { maven { - name = "forge" - url = "https://maven.minecraftforge.net" + name 'forge' + url 'https://maven.minecraftforge.net' } maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" + name 'sonatype' + url 'https://oss.sonatype.org/content/repositories/snapshots/' } maven { - name = "Scala CI dependencies" - url = "https://repo1.maven.org/maven2/" + name 'Scala CI dependencies' + url 'https://repo1.maven.org/maven2/' } maven { - name = "jitpack" - url = "https://jitpack.io" + name 'jitpack' + url 'https://jitpack.io' } } dependencies { @@ -37,21 +44,28 @@ buildscript { } plugins { + id 'java-library' id 'idea' id 'eclipse' id 'scala' id 'maven-publish' - id('org.jetbrains.kotlin.jvm') version ('1.6.10') apply false - id('org.ajoberstar.grgit') version('4.1.1') - id('com.github.johnrengelman.shadow') version('4.0.4') - id('com.palantir.git-version') version('0.13.0') apply false - id('de.undercouch.download') version('5.0.1') + id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false + id 'org.jetbrains.kotlin.kapt' version '1.5.30' apply false + id 'com.google.devtools.ksp' version '1.5.30-1.0.0' apply false + id 'org.ajoberstar.grgit' version '4.1.1' + id 'com.github.johnrengelman.shadow' version '4.0.4' + id 'com.palantir.git-version' version '0.13.0' apply false + id 'de.undercouch.download' version '5.0.1' + id 'com.github.gmazzo.buildconfig' version '3.0.3' apply false + id "com.diffplug.spotless" version "6.7.2" } if (project.file('.git/HEAD').isFile()) { apply plugin: 'com.palantir.git-version' } +def out = services.get(StyledTextOutputFactory).create('an-output') + apply plugin: 'forge' def projectJavaVersion = JavaLanguageVersion.of(8) @@ -70,6 +84,37 @@ idea { } } +// Spotless autoformatter +// See https://github.com/diffplug/spotless/tree/main/plugin-gradle +// Can be locally toggled via spotless:off/spotless:on comments +spotless { + encoding 'UTF-8' + + format 'misc', { + target '.gitignore' + + trimTrailingWhitespace() + indentWithSpaces(4) + endWithNewline() + } + java { + toggleOffOn() + importOrder() + removeUnusedImports() + palantirJavaFormat('1.1.0') // last version supporting jvm 8 + } + kotlin { + toggleOffOn() + ktfmt('0.39') + } + groovyGradle { + toggleOffOn() + importOrder() + target '*.gradle' + greclipse('4.19.0') // last version supporting jvm 8 + } +} + if(JavaVersion.current() != JavaVersion.VERSION_1_8) { throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current()) } @@ -96,6 +141,10 @@ checkPropertyExists("usesShadowedDependencies") checkPropertyExists("developmentEnvironmentUserName") boolean noPublishedSources = project.findProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false +boolean usesMixinDebug = project.findProperty('usesMixinDebug') ?: project.usesMixins.toBoolean() +String channel = project.findProperty('channel') ? project.channel : 'stable' +String mappingsVersion = project.findProperty('mappingsVersion') ? project.mappingsVersion : '12' +String remoteMappings = project.findProperty('remoteMappings') ? project.remoteMappings : 'https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/' String javaSourceDir = "src/main/java/" String scalaSourceDir = "src/main/scala/" @@ -167,8 +216,8 @@ configurations.all { try { 'git config core.fileMode false'.execute() } -catch (Exception e) { - logger.error("\u001B[31mgit isn't installed at all\u001B[0m") +catch (Exception ignored) { + out.style(Style.Failure).println("git isn't installed at all") } // Pulls version first from the VERSION env and then git tag @@ -177,19 +226,22 @@ String versionOverride = System.getenv("VERSION") ?: null try { identifiedVersion = versionOverride == null ? gitVersion() : versionOverride } -catch (Exception e) { - logger.error("\n\u001B[1;31mThis mod must be version controlled by Git AND the repository must provide at least one tag,\n" + - "or the VERSION override must be set! \u001B[32m(Don't download from GitHub using the ZIP option, instead\n" + - "clone the repository, see\u001B[33m https://gtnh.miraheze.org/wiki/Development \u001B[32mfor details.)\u001B[0m\n"); +catch (Exception ignored) { + out.style(Style.Failure).text( + 'This mod must be version controlled by Git AND the repository must provide at least one tag,\n' + + 'or the VERSION override must be set! ').style(Style.SuccessHeader).text('(Do NOT download from GitHub using the ZIP option, instead\n' + + 'clone the repository, see ').style(Style.Info).text('https://gtnh.miraheze.org/wiki/Development').style(Style.SuccessHeader).println(' for details.)' + ) versionOverride = 'NO-GIT-TAG-SET' identifiedVersion = versionOverride } version = minecraftVersion + '-' + identifiedVersion -String modVersion = identifiedVersion +ext { + modVersion = identifiedVersion +} -if( identifiedVersion.equals(versionOverride) ) { - logger.error('\u001B[31m\u001B[7mWe hope you know what you\'re doing using\u001B[0m\u001B[1;34m ' + modVersion + '\u001B[0m\n'); - logger.error('\7\u001B[31mGoing to blindly try to use\u001B[1;34m ' + modVersion + '\u001B[0m\u001B[31m, this probably won\'t work the way you expect!!\u001B[0m\n'); +if(identifiedVersion == versionOverride) { + out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7') } group = modGroup @@ -200,22 +252,25 @@ else { archivesBaseName = modId } - def arguments = [] def jvmArguments = [] -if(usesMixins.toBoolean()) { +if (usesMixins.toBoolean()) { arguments += [ - "--tweakClass org.spongepowered.asm.launch.MixinTweaker" - ] - jvmArguments += [ - "-Dmixin.debug.countInjections=true", "-Dmixin.debug.verbose=true", "-Dmixin.debug.export=true" + "--tweakClass org.spongepowered.asm.launch.MixinTweaker" ] + if (usesMixinDebug.toBoolean()) { + jvmArguments += [ + "-Dmixin.debug.countInjections=true", + "-Dmixin.debug.verbose=true", + "-Dmixin.debug.export=true" + ] + } } minecraft { - version = minecraftVersion + "-" + forgeVersion + "-" + minecraftVersion - runDir = "run" + version = minecraftVersion + '-' + forgeVersion + '-' + minecraftVersion + runDir = 'run' if (replaceGradleTokenInFile) { replaceIn replaceGradleTokenInFile @@ -248,8 +303,8 @@ minecraft { } } -if(file("addon.gradle").exists()) { - apply from: "addon.gradle" +if(file('addon.gradle').exists()) { + apply from: 'addon.gradle' } apply from: 'repositories.gradle' @@ -262,58 +317,63 @@ configurations { repositories { maven { - name = "Overmind forge repo mirror" - url = "https://gregtech.overminddl1.com/" + name 'Overmind forge repo mirror' + url 'https://gregtech.overminddl1.com/' } if(usesMixins.toBoolean()) { maven { - name = "sponge" - url = "https://repo.spongepowered.org/repository/maven-public" + name 'sponge' + url 'https://repo.spongepowered.org/repository/maven-public' } maven { - url = "https://jitpack.io" + url 'https://jitpack.io' } } } dependencies { if(usesMixins.toBoolean()) { - annotationProcessor("org.ow2.asm:asm-debug-all:5.0.3") - annotationProcessor("com.google.guava:guava:24.1.1-jre") - annotationProcessor("com.google.code.gson:gson:2.8.6") - annotationProcessor("org.spongepowered:mixin:0.8-SNAPSHOT") + annotationProcessor('org.ow2.asm:asm-debug-all:5.0.3') + annotationProcessor('com.google.guava:guava:24.1.1-jre') + annotationProcessor('com.google.code.gson:gson:2.8.6') + annotationProcessor('org.spongepowered:mixin:0.8-SNAPSHOT') // using 0.8 to workaround a issue in 0.7 which fails mixin application - compile("com.github.GTNewHorizons:SpongePoweredMixin:0.7.12-GTNH") { + compile('com.github.GTNewHorizons:SpongePoweredMixin:0.7.12-GTNH') { // Mixin includes a lot of dependencies that are too up-to-date - exclude module: "launchwrapper" - exclude module: "guava" - exclude module: "gson" - exclude module: "commons-io" - exclude module: "log4j-core" + exclude module: 'launchwrapper' + exclude module: 'guava' + exclude module: 'gson' + exclude module: 'commons-io' + exclude module: 'log4j-core' } - compile("com.github.GTNewHorizons:SpongeMixins:1.5.0") + compile('com.github.GTNewHorizons:SpongeMixins:1.5.0') } } apply from: 'dependencies.gradle' -def mixingConfigRefMap = "mixins." + modId + ".refmap.json" +def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' def refMap = "${tasks.compileJava.temporaryDir}" + File.separator + mixingConfigRefMap def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg" task generateAssets { - if(usesMixins.toBoolean()) { - getFile("/src/main/resources/mixins." + modId + ".json").text = """{ + if (usesMixins.toBoolean()) { + def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json"); + if (!mixinConfigFile.exists()) { + mixinConfigFile.text = """{ "required": true, "minVersion": "0.7.11", "package": "${modGroup}.${mixinsPackage}", "plugin": "${modGroup}.${mixinPlugin}", "refmap": "${mixingConfigRefMap}", "target": "@env(DEFAULT)", - "compatibilityLevel": "JAVA_8" + "compatibilityLevel": "JAVA_8", + "mixins": [], + "client": [], + "server": [] } - """ + } } } @@ -401,12 +461,11 @@ tasks.withType(JavaExec).configureEach { ) } -processResources -{ +processResources { // this will ensure that this task is redone when the versions change. inputs.property "version", project.version inputs.property "mcversion", project.minecraft.version - + // replace stuff in mcmod.info, nothing else from(sourceSets.main.resources.srcDirs) { include 'mcmod.info' @@ -430,7 +489,7 @@ processResources def getManifestAttributes() { def manifestAttributes = [:] - if(containsMixinsAndOrCoreModOnly.toBoolean() == false && (usesMixins.toBoolean() || coreModClass)) { + if(!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { manifestAttributes += ["FMLCorePluginContainsFMLMod": true] } @@ -446,14 +505,14 @@ def getManifestAttributes() { manifestAttributes += [ "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", "MixinConfigs" : "mixins." + modId + ".json", - "ForceLoadAsMod" : containsMixinsAndOrCoreModOnly.toBoolean() == false + "ForceLoadAsMod" : !containsMixinsAndOrCoreModOnly.toBoolean() ] } return manifestAttributes } task sourcesJar(type: Jar) { - from (sourceSets.main.allJava) + from (sourceSets.main.allSource) from (file("$projectDir/LICENSE")) getArchiveClassifier().set('sources') } @@ -508,7 +567,7 @@ task devJar(type: Jar) { } task apiJar(type: Jar) { - from (sourceSets.main.allJava) { + from (sourceSets.main.allSource) { include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**' } @@ -533,12 +592,15 @@ artifacts { } } -// The gradle metadata includes all of the additional deps that we disabled from POM generation (including forgeBin with no groupID), +// The gradle metadata includes all of the additional deps that we disabled from POM generation (including forgeBin with no groupID), // and isn't strictly needed with the POM so just disable it. tasks.withType(GenerateModuleMetadata) { enabled = false } +// workaround variable hiding in pom processing +def projectConfigs = project.configurations + publishing { publications { maven(MavenPublication) { @@ -547,7 +609,7 @@ publishing { artifact source: shadowJar, classifier: "" } if(!noPublishedSources) { - artifact source: sourcesJar, classifier: "src" + artifact source: sourcesJar, classifier: "sources" } artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev" if (apiPackage) { @@ -558,17 +620,21 @@ publishing { artifactId = System.getenv("ARTIFACT_ID") ?: project.name // Using the identified version, not project.version as it has the prepended 1.7.10 version = System.getenv("RELEASE_VERSION") ?: identifiedVersion - - // remove extra garbage from who knows where + + // remove extra garbage from minecraft and minecraftDeps configuration pom.withXml { - def badPomGroup = ['net.minecraft', 'com.google.code.findbugs', 'org.ow2.asm', 'com.typesafe.akka', 'com.typesafe', 'org.scala-lang', - 'org.scala-lang.plugins', 'net.sf.jopt-simple', 'lzma', 'com.mojang', 'org.apache.commons', 'org.apache.httpcomponents', - 'commons-logging', 'java3d', 'net.sf.trove4j', 'com.ibm.icu', 'com.paulscode', 'io.netty', 'com.google.guava', - 'commons-io', 'commons-codec', 'net.java.jinput', 'net.java.jutils', 'com.google.code.gson', 'org.apache.logging.log4j', - 'org.lwjgl.lwjgl', 'tv.twitch', ''] + def badArtifacts = [:].withDefault {[] as Set} + for (configuration in [projectConfigs.minecraft, projectConfigs.minecraftDeps]) { + for (dependency in configuration.allDependencies) { + badArtifacts[dependency.group == null ? "" : dependency.group] += dependency.name + } + } + // example for specifying extra stuff to ignore + // badArtifacts["org.example.group"] += "artifactName" + Node pomNode = asNode() pomNode.dependencies.'*'.findAll() { - badPomGroup.contains(it.groupId.text()) + badArtifacts[it.groupId.text()].contains(it.artifactId.text()) }.each() { it.parent().remove(it) } @@ -600,7 +666,7 @@ if (isNewBuildScriptVersionAvailable(projectDir.toString())) { if (autoUpdateBuildScript.toBoolean()) { performBuildScriptUpdate(projectDir.toString()) } else { - println("Build script update available! Run 'gradle updateBuildScript'") + out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'") } } @@ -612,7 +678,7 @@ boolean performBuildScriptUpdate(String projectDir) { if (isNewBuildScriptVersionAvailable(projectDir)) { def buildscriptFile = getFile("build.gradle") availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } - print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") return true } return false @@ -643,7 +709,103 @@ configure(updateBuildScript) { description = 'Updates the build script to the latest version' } -// Deobfuscation +// Parameter Deobfuscation + +task deobfParams { + doLast { + + String mcpDir = "$project.gradle.gradleUserHomeDir/caches/minecraft/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion" + String mcpZIP = "$mcpDir/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + String paramsCSV = "$mcpDir/params.csv" + + download.run { + src "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion-$minecraftVersion/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + dest mcpZIP + overwrite false + } + + if(!file(paramsCSV).exists()) { + println("Extracting MCP archive ...") + unzip(mcpZIP, mcpDir) + } + + println("Parsing params.csv ...") + Map params = new HashMap<>() + Files.lines(Paths.get(paramsCSV)).forEach{line -> + String[] cells = line.split(",") + if(cells.length > 2 && cells[0].matches("p_i?\\d+_\\d+_")) { + params.put(cells[0], cells[1]) + } + } + + out.style(Style.Success).println("Modified ${replaceParams(file("$projectDir/src/main/java"), params)} files!") + out.style(Style.Failure).println("Don't forget to verify that the code still works as before!\n It could be broken due to duplicate variables existing now\n or parameters taking priority over other variables.") + } +} + +static int replaceParams(File file, Map params) { + int fileCount = 0 + + if(file.isDirectory()) { + for(File f : file.listFiles()) { + fileCount += replaceParams(f, params) + } + return fileCount + } + println("Visiting ${file.getName()} ...") + try { + String content = new String(Files.readAllBytes(file.toPath())) + int hash = content.hashCode() + params.forEach{key, value -> + content = content.replaceAll(key, value) + } + if(hash != content.hashCode()) { + Files.write(file.toPath(), content.getBytes("UTF-8")) + return 1 + } + } catch(Exception e) { + e.printStackTrace() + } + return 0 +} + +// Credit: bitsnaps (https://gist.github.com/bitsnaps/00947f2dce66f4bbdabc67d7e7b33681) +static unzip(String zipFileName, String outputDir) { + byte[] buffer = new byte[16384] + ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName)) + ZipEntry zipEntry = zis.getNextEntry() + while (zipEntry != null) { + File newFile = new File(outputDir + File.separator, zipEntry.name) + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory $newFile") + } + } else { + // fix for Windows-created archives + File parent = newFile.parentFile + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory $parent") + } + // write file content + FileOutputStream fos = new FileOutputStream(newFile) + int len = 0 + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len) + } + fos.close() + } + zipEntry = zis.getNextEntry() + } + zis.closeEntry() + zis.close() +} + +configure(deobfParams) { + group = 'forgegradle' + description = 'Rename all obfuscated parameter names inherited from Minecraft classes' +} + +// Dependency Deobfuscation def deobf(String sourceURL) { try { @@ -656,7 +818,7 @@ def deobf(String sourceURL) { fileName = fileName.substring(lastSlash + 1) } //get rid of extension: - if(fileName.endsWith(".jar")) { + if(fileName.endsWith(".jar") || fileName.endsWith(".litemod")) { fileName = fileName.substring(0, fileName.lastIndexOf(".")) } @@ -668,26 +830,40 @@ def deobf(String sourceURL) { Collections.reverse(parts) hostName = String.join(".", parts) - return deobf(sourceURL, hostName + "/" + fileName) + return deobf(sourceURL, "$hostName/$fileName") } catch(Exception e) { - return deobf(sourceURL, "deobf/" + String.valueOf(sourceURL.hashCode())) + return deobf(sourceURL, "deobf/${sourceURL.hashCode()}") } } // The method above is to be preferred. Use this method if the filename is not at the end of the URL. -def deobf(String sourceURL, String fileName) { - String cacheDir = System.getProperty("user.home") + "/.gradle/caches/" - String bon2Dir = cacheDir + "forge_gradle/deobf" - String bon2File = bon2Dir + "/BON2-2.5.0.jar" - String obfFile = cacheDir + "modules-2/files-2.1/" + fileName + ".jar" - String deobfFile = cacheDir + "modules-2/files-2.1/" + fileName + "-deobf.jar" - +def deobf(String sourceURL, String rawFileName) { + String bon2Version = "2.5.1" + String fileName = URLDecoder.decode(rawFileName, "UTF-8") + String cacheDir = "$project.gradle.gradleUserHomeDir/caches" + String bon2Dir = "$cacheDir/forge_gradle/deobf" + String bon2File = "$bon2Dir/BON2-${bon2Version}.jar" + String obfFile = "$cacheDir/modules-2/files-2.1/${fileName}.jar" + String deobfFile = "$cacheDir/modules-2/files-2.1/${fileName}-deobf.jar" + if(file(deobfFile).exists()) { return files(deobfFile) } + String mappingsVer + if(remoteMappings) { + String id = "${forgeVersion.split("\\.")[3]}-$minecraftVersion" + String mappingsZIP = "$cacheDir/forge_gradle/maven_downloader/de/oceanlabs/mcp/mcp_snapshot_nodoc/$id/mcp_snapshot_nodoc-${id}.zip" + + zipMappings(mappingsZIP, remoteMappings, bon2Dir) + + mappingsVer = "snapshot_$id" + } else { + mappingsVer = "${channel}_$mappingsVersion" + } + download.run { - src 'https://github.com/GTNewHorizons/BON2/releases/download/2.5.0/BON2-2.5.0.CUSTOM-all.jar' + src "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases/com/github/parker8283/BON2/$bon2Version-CUSTOM/BON2-$bon2Version-CUSTOM-all.jar" dest bon2File quiet true overwrite false @@ -701,18 +877,52 @@ def deobf(String sourceURL, String fileName) { } exec { - commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', '1.7.10', '--mappingsVer', 'stable_12', '--notch' + commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', minecraftVersion, '--mappingsVer', mappingsVer, '--notch' workingDir bon2Dir - standardOutput = new ByteArrayOutputStream() + standardOutput = new FileOutputStream("${deobfFile}.log") } return files(deobfFile) } +def zipMappings(String zipPath, String url, String bon2Dir) { + File zipFile = new File(zipPath) + if(zipFile.exists()) { + return + } + + String fieldsCache = "$bon2Dir/data/fields.csv" + String methodsCache = "$bon2Dir/data/methods.csv" + + download.run { + src "${url}fields.csv" + dest fieldsCache + quiet true + } + download.run { + src "${url}methods.csv" + dest methodsCache + quiet true + } + + zipFile.getParentFile().mkdirs() + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)) + + zos.putNextEntry(new ZipEntry("fields.csv")) + Files.copy(Paths.get(fieldsCache), zos) + zos.closeEntry() + + zos.putNextEntry(new ZipEntry("methods.csv")) + Files.copy(Paths.get(methodsCache), zos) + zos.closeEntry() + + zos.close() +} + // Helper methods def checkPropertyExists(String propertyName) { - if (project.hasProperty(propertyName) == false) { + if (!project.hasProperty(propertyName)) { throw new GradleException("This project requires a property \"" + propertyName + "\"! Please add it your \"gradle.properties\". You can find all properties and their description here: https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/gradle.properties") } } diff --git a/dependencies.gradle b/dependencies.gradle index 0a92ea3..0f83659 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,7 +1,7 @@ // Add your dependencies here dependencies { - compile('com.github.GTNewHorizons:NotEnoughItems:2.2.12-GTNH:dev') + compile('com.github.GTNewHorizons:NotEnoughItems:2.2.12-GTNH:dev') - compile('curse.maven:witchery-69673:2234410') + compile('curse.maven:witchery-69673:2234410') } diff --git a/repositories.gradle b/repositories.gradle index 89c5ce1..bbc7b3e 100644 --- a/repositories.gradle +++ b/repositories.gradle @@ -1,15 +1,15 @@ // Add any additional repositories for your dependencies here repositories { - maven { - name 'GTNH Maven' - url 'http://jenkins.usrv.eu:8081/nexus/content/groups/public/' - allowInsecureProtocol - } - maven { - url 'https://cursemaven.com' - } - maven { - url 'https://jitpack.io' - } + maven { + name 'GTNH Maven' + url 'http://jenkins.usrv.eu:8081/nexus/content/groups/public/' + allowInsecureProtocol + } + maven { + url 'https://cursemaven.com' + } + maven { + url 'https://jitpack.io' + } } diff --git a/src/main/java/alkalus/main/api/RecipeManager.java b/src/main/java/alkalus/main/api/RecipeManager.java index d606ca2..68dea9c 100644 --- a/src/main/java/alkalus/main/api/RecipeManager.java +++ b/src/main/java/alkalus/main/api/RecipeManager.java @@ -1,21 +1,5 @@ package alkalus.main.api; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Hashtable; - -import com.emoniph.witchery.WitcheryRecipes; -import com.emoniph.witchery.crafting.DistilleryRecipes.DistilleryRecipe; -import com.emoniph.witchery.crafting.KettleRecipes.KettleRecipe; -import com.emoniph.witchery.crafting.SpinningRecipes.SpinningRecipe; -import com.emoniph.witchery.infusion.Infusion; -import com.emoniph.witchery.infusion.infusions.creature.CreaturePower; -import com.emoniph.witchery.predictions.Prediction; -import com.emoniph.witchery.ritual.Circle; -import com.emoniph.witchery.ritual.Rite; -import com.emoniph.witchery.ritual.RitualTraits; -import com.emoniph.witchery.ritual.Sacrifice; - import alkalus.main.api.plugin.base.BasePluginWitchery; import alkalus.main.core.WitcheryExtras; import alkalus.main.core.crafting.OvenRecipes.OvenRecipe; @@ -29,390 +13,432 @@ import alkalus.main.core.types.Witchery_SpinningWheel; import alkalus.main.core.util.AutoMap; import alkalus.main.core.util.WitcheryRecipeHandlerInternal; +import com.emoniph.witchery.WitcheryRecipes; +import com.emoniph.witchery.crafting.DistilleryRecipes.DistilleryRecipe; +import com.emoniph.witchery.crafting.KettleRecipes.KettleRecipe; +import com.emoniph.witchery.crafting.SpinningRecipes.SpinningRecipe; +import com.emoniph.witchery.infusion.Infusion; +import com.emoniph.witchery.infusion.infusions.creature.CreaturePower; +import com.emoniph.witchery.predictions.Prediction; +import com.emoniph.witchery.ritual.Circle; +import com.emoniph.witchery.ritual.Rite; +import com.emoniph.witchery.ritual.RitualTraits; +import com.emoniph.witchery.ritual.Sacrifice; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Hashtable; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import scala.collection.mutable.HashTable; /** - * + * * This class brings together the multiple segments spread through the core of the mod. * Should make modification of Witchery only rely on this class for 95% of changes/additions. - * - * This is the single public class to be used externally by other mods, + * + * This is the single public class to be used externally by other mods, * which simply binds together the various other parts into one simple interface. - * - * @author Alkalus + * + * @author Alkalus */ - public class RecipeManager { - /* - * Convenience classes for all the different recipe types. - */ - - /** - * - * Use this class to queue {@link Runnable} objects for loading at the end of each load phase. - * {@link WitcheryExtras} will run all {@link Runnable} objects queued in the order which they are cached. - * It is recommended to have a sub-mod that loads {@code 'before:WitcheryExtras'}, - * however all three load phases can have plugins added prior to this mod starting up. - * @author Alkalus - * - */ - public static class PluginManager { - - /** - * This method MUST be called prior to {@link WitcheryExtras} starting it's {@code PreInit()} phase. - * - * @param basePluginWitchery - {@link BasePluginWitchery} object which you want to load after {@link WitcheryExtras} {@code PreInit()} phase. - * @return - {@link boolean} which always returns true, to signify that the plugin has been queued. - */ - public static boolean loadPluginForPreInit(BasePluginWitchery basePluginWitchery) { - WitcheryExtras.addEventPreInit(basePluginWitchery); - return true; - } - /** - * This method does not need to be called prior to {@link WitcheryExtras} starting it's {@code PreInit()} phase. - * This method MUST be called prior to {@link WitcheryExtras} starting it's {@code Init()} phase. - * - * @param plugin - {@link BasePluginWitchery} object which you want to load after {@link WitcheryExtras} {@code Init()} phase. - * @return - {@link boolean} which always returns true, to signify that the plugin has been queued. - */ - public static boolean loadPluginForInit(BasePluginWitchery plugin) { - WitcheryExtras.addEventInit(plugin); - return true; - } - /** - * This method does not need to be called prior to {@link WitcheryExtras} starting it's {@code PreInit()} phase. - * This method does not need to be called prior to {@link WitcheryExtras} starting it's {@code Init()} phase. - * This method MUST be called prior to {@link WitcheryExtras} starting it's {@code PostInit()} phase. - * - * @param plugin - {@link BasePluginWitchery} object which you want to load after {@link WitcheryExtras} {@code PostInit()} phase. - * @return - {@link boolean} which always returns true, to signify that the plugin has been queued. - */ - public static boolean loadPluginForPostInit(BasePluginWitchery plugin) { - WitcheryExtras.addEventPostInit(plugin); - return true; - } - - } - - public static class WitchesOven { - /** - * @param input1 - The Input Item. - * @param inputString1 - A Valid Oredict String. - * @param jars - The required amount of Jars. - * @param customOutput - A custom ItemStack output. - * @param amt1 - The amount of custom outputs. - * @param outputJarStack - The type of Jar output. - * @param amt2 - The amount of Jars output - * @return - A new {@link OverRecipe} object. - */ - public static synchronized boolean addRecipe(final ItemStack input1, final String inputString1, final int jars, final ItemStack customOutput, final int amt1, final ItemStack outputJarStack, final int amt2) { - return WitcheryRecipeHandlerInternal.addOvenRecipe(input1, inputString1, jars, customOutput, amt1, outputJarStack, amt2); - } - - /** This Function will remove the {@link OvenRecipe} input. - * @param mRecipe - An {@link OvenRecipe} for a recipe you wish to remove. - * @return - {@link boolean} representing whether or not the recipe was removed. - */ - public static synchronized boolean removeRecipe(OvenRecipe mRecipe) { - return WitcheryRecipeHandlerInternal.removeOvenRecipe(mRecipe); - } - /** Finds a {@link OvenRecipe} matching a broad range of inputs. - * @param input1 - An {@link ItemStack}, input 1. - * @param jars - An {@link ItemStack}, amount of Jars used. - * @return - An {@link OvenRecipe} representing the closest matching recipe. - */ - public static synchronized OvenRecipe getOvenResult(ItemStack input1, int jars){ - return Witchery_Oven.getOvenResult(input1, jars); - } - /** This Function will find the first {@link OvenRecipe} it finds that matches the specified output. - * @param outputs - An {@link ItemStack} of the Output, for a recipe you wish to find. - * @return - An {@link OvenRecipe} representing the closest matching recipe. - */ - public static synchronized OvenRecipe findRecipeForOutput(ItemStack result){ - return Witchery_Oven.findRecipeFor(result); - } - /** This Function will find the first {@link OvenRecipe} it finds that matches the specified ingredient. - * @param outputs - An {@link ItemStack} of the ingredient, for a recipe you wish to find. - * @return - A {@link OvenRecipe} representing the closest matching recipe. - */ - public static synchronized OvenRecipe findRecipeUsingIngredient(ItemStack ingredient){ - return Witchery_Oven.findRecipeUsing(ingredient); - } - } - - public static class SpinningWheel { - - /** - * - * @param aInputFibre - The Item to be spun. - * @param aOutput - The item produced. - * @param aModifiers - Modifiers to change the recipe. - * @return - {@link boolean} representing whether or not the recipe was added. - */ - public static boolean addRecipe(ItemStack aInputFibre, ItemStack aOutput, ItemStack[] aModifiers) { - return WitcheryRecipeHandlerInternal.addSpinningWheelRecipe(aOutput, aInputFibre, aModifiers); - } - - /** This Function will remove the closest matching recipe. - * @param result - An {@link ItemStack}, The result of the spinning recipe. - * @param fibre - An {@link ItemStack}, The 'fibre' used to produce the result.. - * @param modifiers - An {@link ItemStack}, The items used to modify this recipe (Can be null). - * @return - {@link boolean} representing whether or not the recipe was removed. - */ - public static boolean removeRecipe(ItemStack result, ItemStack fibre, ItemStack... modifiers) { - return WitcheryRecipeHandlerInternal.removeSpinningWheelRecipe(result, fibre, modifiers); - } - - /** This Function will remove the {@link SpinningRecipe} input. - * @param outputs - An {@link SpinningRecipe} for a recipe you wish to remove. - * @return - {@link boolean} representing whether or not the recipe was removed. - */ - public static synchronized boolean removeRecipe(SpinningRecipe mRecipe) { - return WitcheryRecipeHandlerInternal.removeSpinningRecipe(mRecipe); - } - - /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified output. - * @param fibre - The Input Used - * @param modifiers - Modifiers used (Can be null) - * @return - An {@link SpinningRecipe} representing the closest matching recipe. - */ - public static synchronized SpinningRecipe getRecipe(ItemStack fibre, ItemStack[] modifiers) { - return Witchery_SpinningWheel.getRecipe(fibre, modifiers); - } - - /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified output. - * @param outputs - An {@link ItemStack} of the Output, for a recipe you wish to find. - * @return - An {@link SpinningRecipe} representing the closest matching recipe. - */ - public static synchronized SpinningRecipe findRecipeFor(ItemStack result) { - return Witchery_SpinningWheel.findRecipeFor(result); - } - - /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified ingredient. - * @param outputs - An {@link ItemStack} of the ingredient, for a recipe you wish to find. May be the fibre or a modifier. - * @return - A {@link SpinningRecipe} representing the closest matching recipe. - */ - public static synchronized SpinningRecipe findRecipeUsing(ItemStack ingredient) { - return Witchery_SpinningWheel.findRecipeUsing(ingredient); - } - - /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified input. - * @param outputs - An {@link ItemStack} of the fibre used, for a recipe you wish to find. - * @return - A {@link SpinningRecipe} representing the closest matching recipe. - */ - public static synchronized SpinningRecipe findRecipeUsingFibre(ItemStack ingredient) { - return Witchery_SpinningWheel.findRecipeUsingFibre(ingredient); - } - - } - - public static class Distillery { - /** @param input1 - First Input Item - * @param input2 - Secondary Input Item - * @param jars - An {@link int} that represents the required amount of empty jars. - * @param output1 - First Output Item - * @param output2 - Second Output Item - * @param output3 - Third Output Item - * @param output4 - Fourth Output Item - * @return - {@link boolean} representing whether or not the recipe was added. - */ - public static synchronized boolean addRecipe(ItemStack input1, ItemStack input2, int jars, ItemStack output1, ItemStack output2, ItemStack output3, ItemStack output4) { - return WitcheryRecipeHandlerInternal.addDistilleryRecipe(input1, input2, jars, output1, output2, output3, output4); - } - /** This Function will remove the {@link KettleRecipe} input. - * @param outputs - An {@link DistilleryRecipe} for a recipe you wish to remove. - * @return - {@link boolean} representing whether or not the recipe was removed. - */ - public static synchronized boolean removeRecipe(DistilleryRecipe mRecipe) { - return WitcheryRecipeHandlerInternal.removeDistilleryRecipe(mRecipe); - } - /** Finds a {@link DistilleryRecipe} matching a broad range of inputs. - * @param input1 - An {@link ItemStack}, input 1. - * @param input2 - An {@link ItemStack}, input 2. - * @param jars - An {@link ItemStack}, input 3. This input slot is for Jars. - * @return - An {@link DistilleryRecipe} representing the closest matching recipe. - */ - public static synchronized DistilleryRecipe getDistillingResult(ItemStack input1, ItemStack input2, ItemStack jars){ - return Witchery_Distillery.getDistillingResult(input1, input2, jars); - } - /** This Function will find the first {@link DistilleryRecipe} it finds that matches the specified output. - * @param outputs - An {@link ItemStack} of the Output, for a recipe you wish to find. - * @return - An {@link DistilleryRecipe} representing the closest matching recipe. - */ - public static synchronized DistilleryRecipe findRecipeForOutput(ItemStack result){ - return Witchery_Distillery.findRecipeFor(result); - } - /** This Function will find the first {@link DistilleryRecipe} it finds that matches the specified ingredient. - * @param outputs - An {@link ItemStack} of the ingredient, for a recipe you wish to find. - * @return - A {@link DistilleryRecipe} representing the closest matching recipe. - */ - public static synchronized DistilleryRecipe findRecipeUsingIngredient(ItemStack ingredient){ - return Witchery_Distillery.findRecipeUsing(ingredient); - } - } - - public static class Kettle { - /** @param output - {@link ItemStack} The Output Stack. - * @param hatBonus - {@link int} The bonus granted from wearing {@value Witchery} Hats. - * @param familiarType - {@link int} The ID of the familiar required, can be 0. - * @param powerRequired - {@link float} The amount of power required from your Altar, can be 0. - * @param color - {@link int} The colour of the brew when the {@link KettleRecipe} is processing. - * @param dimension - {@link int} The dimension ID required. Can't be left as 0 to allow all Dims. - * @param inBook - {@link boolean} Does this recipe show up in the Kettle recipe book? - * @param inputs - {@link ItemStack} {@code ||} {@link ItemStack}[] of Input Items. - * @return - {@link boolean} representing whether or not the recipe was added. - */ - public static synchronized boolean addRecipe(ItemStack output, int hatBonus, int familiarType, float powerRequired, int color, int dimension, boolean inBook, ItemStack... inputs) { - return WitcheryRecipeHandlerInternal.addKettleRecipe(output, hatBonus, familiarType, powerRequired, color, dimension, inBook, inputs); - } - - /** This Function will remove the first {@link KettleRecipe} it finds that matches the specified output. - * @param mOutput - An {@link ItemStack} of the Output, for a recipe you wish to remove. - * @return - {@link boolean} representing whether or not the recipe was removed. - */ - public static synchronized boolean removeRecipe(ItemStack mOutput) { - return WitcheryRecipeHandlerInternal.removeKettleRecipe(mOutput); - } - - /** @param inputs - An {@link ItemStack} array which contains some if not all of the inputs for the recipe you're trying to find. - * @param output - An {@link ItemStack} of the output item for the recipe you are trying to find. - * @return - The {@link KettleRecipe} closest matching your search parameters. - */ - public static KettleRecipe findRecipeWithSomeInputsAndAnOutput(ItemStack[] inputs, ItemStack output) { - return Witchery_Kettle.findRecipeWithSomeInputsAndAnOutput(inputs, output); - } - - /** @param result - An {@link ItemStack}, used to find a {@link HashMap} full of all {@link KettleRecipe}s with this output. - * @return - An {@link AutoMap} Which holds all matching recipes containing {@code 'result'} as an output. - */ - public static AutoMap findRecipesFor(final ItemStack result) { - return Witchery_Kettle.findRecipesFor(result); - } - } - - public static class CreaturePowers { - /** @param power - A new {@link CreaturePower} to be added to the registry. - * @return - A {@link boolean} which reflects registry addition. - */ - public static synchronized boolean add(CreaturePower power) { - return WitcheryRecipeHandlerInternal.addNewCreaturePower(power); - } - /** This Function will remove the specified {@link CreaturePower}. - * @param power - An {@link CreaturePower} you wish to remove. - * @return - {@link boolean} representing whether or not the {@link CreaturePower} was removed. - */ - public static synchronized boolean remove(CreaturePower power) { - return WitcheryRecipeHandlerInternal.removeCreaturePower(power); - } - - /** @param entity - The {@link EntityLiving} to find a {@link CreaturePower} for. - * @return - Matching {@link CreaturePower}. - */ - public static synchronized CreaturePower getCreaturePower(EntityLiving entity) { - return Witchery_CreaturePower.getCreaturePower(entity); - } - /** @param entity - The Entity ID to use to find a {@link CreaturePower}. - * @return - Matching {@link CreaturePower}. - */ - public static synchronized CreaturePower getCreaturePower(int entityID) { - return Witchery_CreaturePower.getCreaturePower(entityID); - } - } - - public static class RitesAndRituals { - /** @param ritualID - Byte Value between 0-127. - * @param bookIndex - Unsure, possibly look at other recipes in {@link WitcheryRecipes} for better examples. - * Otherwise, just use ID+100 if you are unsure and want recipes to work as expected. - * @param rite - The {@link Rite} that you wish to add to the registry. - * @param initialSacrifice - The {@link Sacrifice} that is required. - * @param traits - An {@link EnumSet} filled with {@link RitualTraits}. - * @param circles - The {@link Circle}s that are required, can be an array or several single objects. - * @return - A {@link boolean} reflecting the addition of the new Rite to the Registry. - */ - public static synchronized boolean add(int ritualID, int bookIndex, Rite rite, Sacrifice initialSacrifice, EnumSet traits, Circle... circles) { - return WitcheryRecipeHandlerInternal.addNewRiteToRiteRegistry(ritualID, bookIndex, rite, initialSacrifice, traits, circles); - } - /** This Function will remove the {@link Rite} specified by it's ID.. - * @param ritualID - A {@link int} representation of the Rite you wish to remove. - * @return - {@link boolean} representing whether or not the {@link Rite} was removed. - */ - public static synchronized boolean remove(int ritualID) { - return WitcheryRecipeHandlerInternal.removeRiteFromRiteRegistry(ritualID); - } - /** Finds the last/highest used ID used by any {@link Rite}. - * @return - {@link int} containing the last/highest ID. - */ - public static int getLastUsedRitualID() { - return Witchery_Rite.getLastUsedRiteID(); - } - } - - public static class Predictions { - /** @param prediction - A new {@link Prediction} to be added to the registry. - * @return - A {@link boolean} which reflects registry addition. - */ - public static synchronized boolean add(Prediction prediction) { - return WitcheryRecipeHandlerInternal.addNewPrediction(prediction); - } - /** This Function will remove the specified {@link Prediction}. - * @param power - A {@link Prediction} you wish to remove. - * @return - {@link boolean} representing whether or not the {@link Prediction} was removed. - */ - public static synchronized boolean remove(Prediction prediction) { - return WitcheryRecipeHandlerInternal.removePrediction(prediction); - } - /** @return - {@link HashTable} containing all currently stored {@link Prediction}s. - */ - public static synchronized Hashtable getPredictions() { - return Witchery_Predictions.getPredictions(); - } - /** - * @param aID - The ID the desired prediction is registered to. - * @return - {@link Prediction} bound to ID. - */ - public static synchronized Prediction getPrediction(int aID) { - return getPredictions().get(aID); - } - } - - public static class Infusions { - /** Allows adding a new Infusion. - * @param infusion - The {@link Infusion} object you wish to add to the registry. - * @return - A {@link boolean} that reflects if the new object was added. - */ - public static synchronized boolean add(Infusion infusion) { - return WitcheryRecipeHandlerInternal.addNewInfusion(infusion); - } - /** This Function will remove the specified {@link Infusion}. - * @param power - A {@link Infusion} you wish to remove. - * @return - {@link boolean} representing whether or not the {@link Infusion} was removed. - */ - public static synchronized boolean remove(Infusion infusion) { - return WitcheryRecipeHandlerInternal.removeInfusion(infusion); - } - /** @param i - {@link int} - The {@link Infusion}'s ID. - * @return - The {@link Infusion} found for the ID provided, possibly {@link null}. - */ - public static Infusion getInfusion(int i) { - return Witchery_Infusion.getInfusion(i); - } - /** @param i - {@link EntityPlayer} - The player you wish to get the {@link Infusion} from. - * @return - The {@link Infusion} found for the player provided, possibly {@link null}. - */ - public static Infusion getInfusionOnPlayer(EntityPlayer player) { - return Witchery_Infusion.getInfusionOnPlayer(player); - } - /** Finds the last/highest used ID used by any infusion. - * @return - {@link int} containing the last/highest ID. - */ - public static int getLastUsedInfusionID() { - return Witchery_Infusion.getLastUsedInfusionID(); - } - } - + /* + * Convenience classes for all the different recipe types. + */ + + /** + * + * Use this class to queue {@link Runnable} objects for loading at the end of each load phase. + * {@link WitcheryExtras} will run all {@link Runnable} objects queued in the order which they are cached. + * It is recommended to have a sub-mod that loads {@code 'before:WitcheryExtras'}, + * however all three load phases can have plugins added prior to this mod starting up. + * @author Alkalus + * + */ + public static class PluginManager { + + /** + * This method MUST be called prior to {@link WitcheryExtras} starting it's {@code PreInit()} phase. + * + * @param basePluginWitchery - {@link BasePluginWitchery} object which you want to load after {@link WitcheryExtras} {@code PreInit()} phase. + * @return - {@link boolean} which always returns true, to signify that the plugin has been queued. + */ + public static boolean loadPluginForPreInit(BasePluginWitchery basePluginWitchery) { + WitcheryExtras.addEventPreInit(basePluginWitchery); + return true; + } + /** + * This method does not need to be called prior to {@link WitcheryExtras} starting it's {@code PreInit()} phase. + * This method MUST be called prior to {@link WitcheryExtras} starting it's {@code Init()} phase. + * + * @param plugin - {@link BasePluginWitchery} object which you want to load after {@link WitcheryExtras} {@code Init()} phase. + * @return - {@link boolean} which always returns true, to signify that the plugin has been queued. + */ + public static boolean loadPluginForInit(BasePluginWitchery plugin) { + WitcheryExtras.addEventInit(plugin); + return true; + } + /** + * This method does not need to be called prior to {@link WitcheryExtras} starting it's {@code PreInit()} phase. + * This method does not need to be called prior to {@link WitcheryExtras} starting it's {@code Init()} phase. + * This method MUST be called prior to {@link WitcheryExtras} starting it's {@code PostInit()} phase. + * + * @param plugin - {@link BasePluginWitchery} object which you want to load after {@link WitcheryExtras} {@code PostInit()} phase. + * @return - {@link boolean} which always returns true, to signify that the plugin has been queued. + */ + public static boolean loadPluginForPostInit(BasePluginWitchery plugin) { + WitcheryExtras.addEventPostInit(plugin); + return true; + } + } + + public static class WitchesOven { + /** + * @param input1 - The Input Item. + * @param inputString1 - A Valid Oredict String. + * @param jars - The required amount of Jars. + * @param customOutput - A custom ItemStack output. + * @param amt1 - The amount of custom outputs. + * @param outputJarStack - The type of Jar output. + * @param amt2 - The amount of Jars output + * @return - A new {@link OverRecipe} object. + */ + public static synchronized boolean addRecipe( + final ItemStack input1, + final String inputString1, + final int jars, + final ItemStack customOutput, + final int amt1, + final ItemStack outputJarStack, + final int amt2) { + return WitcheryRecipeHandlerInternal.addOvenRecipe( + input1, inputString1, jars, customOutput, amt1, outputJarStack, amt2); + } + + /** This Function will remove the {@link OvenRecipe} input. + * @param mRecipe - An {@link OvenRecipe} for a recipe you wish to remove. + * @return - {@link boolean} representing whether or not the recipe was removed. + */ + public static synchronized boolean removeRecipe(OvenRecipe mRecipe) { + return WitcheryRecipeHandlerInternal.removeOvenRecipe(mRecipe); + } + /** Finds a {@link OvenRecipe} matching a broad range of inputs. + * @param input1 - An {@link ItemStack}, input 1. + * @param jars - An {@link ItemStack}, amount of Jars used. + * @return - An {@link OvenRecipe} representing the closest matching recipe. + */ + public static synchronized OvenRecipe getOvenResult(ItemStack input1, int jars) { + return Witchery_Oven.getOvenResult(input1, jars); + } + /** This Function will find the first {@link OvenRecipe} it finds that matches the specified output. + * @param outputs - An {@link ItemStack} of the Output, for a recipe you wish to find. + * @return - An {@link OvenRecipe} representing the closest matching recipe. + */ + public static synchronized OvenRecipe findRecipeForOutput(ItemStack result) { + return Witchery_Oven.findRecipeFor(result); + } + /** This Function will find the first {@link OvenRecipe} it finds that matches the specified ingredient. + * @param outputs - An {@link ItemStack} of the ingredient, for a recipe you wish to find. + * @return - A {@link OvenRecipe} representing the closest matching recipe. + */ + public static synchronized OvenRecipe findRecipeUsingIngredient(ItemStack ingredient) { + return Witchery_Oven.findRecipeUsing(ingredient); + } + } + + public static class SpinningWheel { + + /** + * + * @param aInputFibre - The Item to be spun. + * @param aOutput - The item produced. + * @param aModifiers - Modifiers to change the recipe. + * @return - {@link boolean} representing whether or not the recipe was added. + */ + public static boolean addRecipe(ItemStack aInputFibre, ItemStack aOutput, ItemStack[] aModifiers) { + return WitcheryRecipeHandlerInternal.addSpinningWheelRecipe(aOutput, aInputFibre, aModifiers); + } + + /** This Function will remove the closest matching recipe. + * @param result - An {@link ItemStack}, The result of the spinning recipe. + * @param fibre - An {@link ItemStack}, The 'fibre' used to produce the result.. + * @param modifiers - An {@link ItemStack}, The items used to modify this recipe (Can be null). + * @return - {@link boolean} representing whether or not the recipe was removed. + */ + public static boolean removeRecipe(ItemStack result, ItemStack fibre, ItemStack... modifiers) { + return WitcheryRecipeHandlerInternal.removeSpinningWheelRecipe(result, fibre, modifiers); + } + + /** This Function will remove the {@link SpinningRecipe} input. + * @param outputs - An {@link SpinningRecipe} for a recipe you wish to remove. + * @return - {@link boolean} representing whether or not the recipe was removed. + */ + public static synchronized boolean removeRecipe(SpinningRecipe mRecipe) { + return WitcheryRecipeHandlerInternal.removeSpinningRecipe(mRecipe); + } + + /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified output. + * @param fibre - The Input Used + * @param modifiers - Modifiers used (Can be null) + * @return - An {@link SpinningRecipe} representing the closest matching recipe. + */ + public static synchronized SpinningRecipe getRecipe(ItemStack fibre, ItemStack[] modifiers) { + return Witchery_SpinningWheel.getRecipe(fibre, modifiers); + } + + /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified output. + * @param outputs - An {@link ItemStack} of the Output, for a recipe you wish to find. + * @return - An {@link SpinningRecipe} representing the closest matching recipe. + */ + public static synchronized SpinningRecipe findRecipeFor(ItemStack result) { + return Witchery_SpinningWheel.findRecipeFor(result); + } + + /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified ingredient. + * @param outputs - An {@link ItemStack} of the ingredient, for a recipe you wish to find. May be the fibre or a modifier. + * @return - A {@link SpinningRecipe} representing the closest matching recipe. + */ + public static synchronized SpinningRecipe findRecipeUsing(ItemStack ingredient) { + return Witchery_SpinningWheel.findRecipeUsing(ingredient); + } + + /** This Function will find the first {@link SpinningRecipe} it finds that matches the specified input. + * @param outputs - An {@link ItemStack} of the fibre used, for a recipe you wish to find. + * @return - A {@link SpinningRecipe} representing the closest matching recipe. + */ + public static synchronized SpinningRecipe findRecipeUsingFibre(ItemStack ingredient) { + return Witchery_SpinningWheel.findRecipeUsingFibre(ingredient); + } + } + + public static class Distillery { + /** @param input1 - First Input Item + * @param input2 - Secondary Input Item + * @param jars - An {@link int} that represents the required amount of empty jars. + * @param output1 - First Output Item + * @param output2 - Second Output Item + * @param output3 - Third Output Item + * @param output4 - Fourth Output Item + * @return - {@link boolean} representing whether or not the recipe was added. + */ + public static synchronized boolean addRecipe( + ItemStack input1, + ItemStack input2, + int jars, + ItemStack output1, + ItemStack output2, + ItemStack output3, + ItemStack output4) { + return WitcheryRecipeHandlerInternal.addDistilleryRecipe( + input1, input2, jars, output1, output2, output3, output4); + } + /** This Function will remove the {@link KettleRecipe} input. + * @param outputs - An {@link DistilleryRecipe} for a recipe you wish to remove. + * @return - {@link boolean} representing whether or not the recipe was removed. + */ + public static synchronized boolean removeRecipe(DistilleryRecipe mRecipe) { + return WitcheryRecipeHandlerInternal.removeDistilleryRecipe(mRecipe); + } + /** Finds a {@link DistilleryRecipe} matching a broad range of inputs. + * @param input1 - An {@link ItemStack}, input 1. + * @param input2 - An {@link ItemStack}, input 2. + * @param jars - An {@link ItemStack}, input 3. This input slot is for Jars. + * @return - An {@link DistilleryRecipe} representing the closest matching recipe. + */ + public static synchronized DistilleryRecipe getDistillingResult( + ItemStack input1, ItemStack input2, ItemStack jars) { + return Witchery_Distillery.getDistillingResult(input1, input2, jars); + } + /** This Function will find the first {@link DistilleryRecipe} it finds that matches the specified output. + * @param outputs - An {@link ItemStack} of the Output, for a recipe you wish to find. + * @return - An {@link DistilleryRecipe} representing the closest matching recipe. + */ + public static synchronized DistilleryRecipe findRecipeForOutput(ItemStack result) { + return Witchery_Distillery.findRecipeFor(result); + } + /** This Function will find the first {@link DistilleryRecipe} it finds that matches the specified ingredient. + * @param outputs - An {@link ItemStack} of the ingredient, for a recipe you wish to find. + * @return - A {@link DistilleryRecipe} representing the closest matching recipe. + */ + public static synchronized DistilleryRecipe findRecipeUsingIngredient(ItemStack ingredient) { + return Witchery_Distillery.findRecipeUsing(ingredient); + } + } + + public static class Kettle { + /** @param output - {@link ItemStack} The Output Stack. + * @param hatBonus - {@link int} The bonus granted from wearing {@value Witchery} Hats. + * @param familiarType - {@link int} The ID of the familiar required, can be 0. + * @param powerRequired - {@link float} The amount of power required from your Altar, can be 0. + * @param color - {@link int} The colour of the brew when the {@link KettleRecipe} is processing. + * @param dimension - {@link int} The dimension ID required. Can't be left as 0 to allow all Dims. + * @param inBook - {@link boolean} Does this recipe show up in the Kettle recipe book? + * @param inputs - {@link ItemStack} {@code ||} {@link ItemStack}[] of Input Items. + * @return - {@link boolean} representing whether or not the recipe was added. + */ + public static synchronized boolean addRecipe( + ItemStack output, + int hatBonus, + int familiarType, + float powerRequired, + int color, + int dimension, + boolean inBook, + ItemStack... inputs) { + return WitcheryRecipeHandlerInternal.addKettleRecipe( + output, hatBonus, familiarType, powerRequired, color, dimension, inBook, inputs); + } + + /** This Function will remove the first {@link KettleRecipe} it finds that matches the specified output. + * @param mOutput - An {@link ItemStack} of the Output, for a recipe you wish to remove. + * @return - {@link boolean} representing whether or not the recipe was removed. + */ + public static synchronized boolean removeRecipe(ItemStack mOutput) { + return WitcheryRecipeHandlerInternal.removeKettleRecipe(mOutput); + } + + /** @param inputs - An {@link ItemStack} array which contains some if not all of the inputs for the recipe you're trying to find. + * @param output - An {@link ItemStack} of the output item for the recipe you are trying to find. + * @return - The {@link KettleRecipe} closest matching your search parameters. + */ + public static KettleRecipe findRecipeWithSomeInputsAndAnOutput(ItemStack[] inputs, ItemStack output) { + return Witchery_Kettle.findRecipeWithSomeInputsAndAnOutput(inputs, output); + } + + /** @param result - An {@link ItemStack}, used to find a {@link HashMap} full of all {@link KettleRecipe}s with this output. + * @return - An {@link AutoMap} Which holds all matching recipes containing {@code 'result'} as an output. + */ + public static AutoMap findRecipesFor(final ItemStack result) { + return Witchery_Kettle.findRecipesFor(result); + } + } + + public static class CreaturePowers { + /** @param power - A new {@link CreaturePower} to be added to the registry. + * @return - A {@link boolean} which reflects registry addition. + */ + public static synchronized boolean add(CreaturePower power) { + return WitcheryRecipeHandlerInternal.addNewCreaturePower(power); + } + /** This Function will remove the specified {@link CreaturePower}. + * @param power - An {@link CreaturePower} you wish to remove. + * @return - {@link boolean} representing whether or not the {@link CreaturePower} was removed. + */ + public static synchronized boolean remove(CreaturePower power) { + return WitcheryRecipeHandlerInternal.removeCreaturePower(power); + } + + /** @param entity - The {@link EntityLiving} to find a {@link CreaturePower} for. + * @return - Matching {@link CreaturePower}. + */ + public static synchronized CreaturePower getCreaturePower(EntityLiving entity) { + return Witchery_CreaturePower.getCreaturePower(entity); + } + /** @param entity - The Entity ID to use to find a {@link CreaturePower}. + * @return - Matching {@link CreaturePower}. + */ + public static synchronized CreaturePower getCreaturePower(int entityID) { + return Witchery_CreaturePower.getCreaturePower(entityID); + } + } + + public static class RitesAndRituals { + /** @param ritualID - Byte Value between 0-127. + * @param bookIndex - Unsure, possibly look at other recipes in {@link WitcheryRecipes} for better examples. + * Otherwise, just use ID+100 if you are unsure and want recipes to work as expected. + * @param rite - The {@link Rite} that you wish to add to the registry. + * @param initialSacrifice - The {@link Sacrifice} that is required. + * @param traits - An {@link EnumSet} filled with {@link RitualTraits}. + * @param circles - The {@link Circle}s that are required, can be an array or several single objects. + * @return - A {@link boolean} reflecting the addition of the new Rite to the Registry. + */ + public static synchronized boolean add( + int ritualID, + int bookIndex, + Rite rite, + Sacrifice initialSacrifice, + EnumSet traits, + Circle... circles) { + return WitcheryRecipeHandlerInternal.addNewRiteToRiteRegistry( + ritualID, bookIndex, rite, initialSacrifice, traits, circles); + } + /** This Function will remove the {@link Rite} specified by it's ID.. + * @param ritualID - A {@link int} representation of the Rite you wish to remove. + * @return - {@link boolean} representing whether or not the {@link Rite} was removed. + */ + public static synchronized boolean remove(int ritualID) { + return WitcheryRecipeHandlerInternal.removeRiteFromRiteRegistry(ritualID); + } + /** Finds the last/highest used ID used by any {@link Rite}. + * @return - {@link int} containing the last/highest ID. + */ + public static int getLastUsedRitualID() { + return Witchery_Rite.getLastUsedRiteID(); + } + } + + public static class Predictions { + /** @param prediction - A new {@link Prediction} to be added to the registry. + * @return - A {@link boolean} which reflects registry addition. + */ + public static synchronized boolean add(Prediction prediction) { + return WitcheryRecipeHandlerInternal.addNewPrediction(prediction); + } + /** This Function will remove the specified {@link Prediction}. + * @param power - A {@link Prediction} you wish to remove. + * @return - {@link boolean} representing whether or not the {@link Prediction} was removed. + */ + public static synchronized boolean remove(Prediction prediction) { + return WitcheryRecipeHandlerInternal.removePrediction(prediction); + } + /** @return - {@link HashTable} containing all currently stored {@link Prediction}s. + */ + public static synchronized Hashtable getPredictions() { + return Witchery_Predictions.getPredictions(); + } + /** + * @param aID - The ID the desired prediction is registered to. + * @return - {@link Prediction} bound to ID. + */ + public static synchronized Prediction getPrediction(int aID) { + return getPredictions().get(aID); + } + } + + public static class Infusions { + /** Allows adding a new Infusion. + * @param infusion - The {@link Infusion} object you wish to add to the registry. + * @return - A {@link boolean} that reflects if the new object was added. + */ + public static synchronized boolean add(Infusion infusion) { + return WitcheryRecipeHandlerInternal.addNewInfusion(infusion); + } + /** This Function will remove the specified {@link Infusion}. + * @param power - A {@link Infusion} you wish to remove. + * @return - {@link boolean} representing whether or not the {@link Infusion} was removed. + */ + public static synchronized boolean remove(Infusion infusion) { + return WitcheryRecipeHandlerInternal.removeInfusion(infusion); + } + /** @param i - {@link int} - The {@link Infusion}'s ID. + * @return - The {@link Infusion} found for the ID provided, possibly {@link null}. + */ + public static Infusion getInfusion(int i) { + return Witchery_Infusion.getInfusion(i); + } + /** @param i - {@link EntityPlayer} - The player you wish to get the {@link Infusion} from. + * @return - The {@link Infusion} found for the player provided, possibly {@link null}. + */ + public static Infusion getInfusionOnPlayer(EntityPlayer player) { + return Witchery_Infusion.getInfusionOnPlayer(player); + } + /** Finds the last/highest used ID used by any infusion. + * @return - {@link int} containing the last/highest ID. + */ + public static int getLastUsedInfusionID() { + return Witchery_Infusion.getLastUsedInfusionID(); + } + } } - diff --git a/src/main/java/alkalus/main/api/plugin/ExamplePlugin.java b/src/main/java/alkalus/main/api/plugin/ExamplePlugin.java index 255ef1a..e394b53 100644 --- a/src/main/java/alkalus/main/api/plugin/ExamplePlugin.java +++ b/src/main/java/alkalus/main/api/plugin/ExamplePlugin.java @@ -1,74 +1,70 @@ package alkalus.main.api.plugin; - +import alkalus.main.api.RecipeManager; +import alkalus.main.api.plugin.base.BasePluginWitchery; import com.emoniph.witchery.Witchery; import com.emoniph.witchery.predictions.Prediction; import com.emoniph.witchery.util.Dye; - import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import alkalus.main.api.RecipeManager; -import alkalus.main.api.plugin.base.BasePluginWitchery; - public class ExamplePlugin extends BasePluginWitchery { - public ExamplePlugin() { - super(new LoadPhase[] {LoadPhase.INIT, LoadPhase.POSTINIT}); - } - - @Override - public String getPluginName() { - return "Example_Plugin"; - } - - @Override - public boolean preInit() { - return false; - } + public ExamplePlugin() { + super(new LoadPhase[] {LoadPhase.INIT, LoadPhase.POSTINIT}); + } - @Override - public boolean init() { - //Add Recipes Here - RecipeManager.Kettle.addRecipe( - Witchery.Items.GENERIC.itemBrewOfThorns.createStack(3), //Output - 1, //Witch Hat Bonus - 0, //Familiar ID - 0.0f, //Alter Power Required - -10027232, //Kettle Brew Colour - 0, //Dimension ID Required (Best left 0) - true, //Does this show in the Kettle Recipes book? - new ItemStack[]{ //Inputs - Dye.CACTUS_GREEN.createStack(), - Witchery.Items.GENERIC.itemDiamondVapour.createStack(), - Witchery.Items.GENERIC.itemOdourOfPurity.createStack(), - Witchery.Items.GENERIC.itemMandrakeRoot.createStack() - }); + @Override + public String getPluginName() { + return "Example_Plugin"; + } + @Override + public boolean preInit() { + return false; + } - RecipeManager.Distillery.addRecipe( - new ItemStack(Items.diamond), //Input A - Witchery.Items.GENERIC.itemOilOfVitriol.createStack(), //Input B - 3, //Required Empty Jar Count - Witchery.Items.GENERIC.itemMandrakeRoot.createStack(), //Output A - Witchery.Items.GENERIC.itemDiamondVapour.createStack(), //Output B - Witchery.Items.GENERIC.itemOdourOfPurity.createStack(), //Output C - (ItemStack) null); //Output D - return true; - } + @Override + public boolean init() { + // Add Recipes Here + RecipeManager.Kettle.addRecipe( + Witchery.Items.GENERIC.itemBrewOfThorns.createStack(3), // Output + 1, // Witch Hat Bonus + 0, // Familiar ID + 0.0f, // Alter Power Required + -10027232, // Kettle Brew Colour + 0, // Dimension ID Required (Best left 0) + true, // Does this show in the Kettle Recipes book? + new ItemStack[] { // Inputs + Dye.CACTUS_GREEN.createStack(), + Witchery.Items.GENERIC.itemDiamondVapour.createStack(), + Witchery.Items.GENERIC.itemOdourOfPurity.createStack(), + Witchery.Items.GENERIC.itemMandrakeRoot.createStack() + }); - @Override - public boolean postInit() { - //Remove Recipes Here - RecipeManager.Kettle.removeRecipe(Witchery.Items.GENERIC.itemHappenstanceOil.createStack()); - RecipeManager.Distillery.removeRecipe(RecipeManager.Distillery.findRecipeUsingIngredient(new ItemStack(Items.diamond))); - RecipeManager.RitesAndRituals.remove((byte) 1); - RecipeManager.Infusions.remove(RecipeManager.Infusions.getInfusion(3)); - for (Prediction H : RecipeManager.Predictions.getPredictions().values()) { - RecipeManager.Predictions.remove(H); - } - RecipeManager.CreaturePowers.remove(RecipeManager.CreaturePowers.getCreaturePower(18)); - return true; - } + RecipeManager.Distillery.addRecipe( + new ItemStack(Items.diamond), // Input A + Witchery.Items.GENERIC.itemOilOfVitriol.createStack(), // Input B + 3, // Required Empty Jar Count + Witchery.Items.GENERIC.itemMandrakeRoot.createStack(), // Output A + Witchery.Items.GENERIC.itemDiamondVapour.createStack(), // Output B + Witchery.Items.GENERIC.itemOdourOfPurity.createStack(), // Output C + (ItemStack) null); // Output D + return true; + } + @Override + public boolean postInit() { + // Remove Recipes Here + RecipeManager.Kettle.removeRecipe(Witchery.Items.GENERIC.itemHappenstanceOil.createStack()); + RecipeManager.Distillery.removeRecipe( + RecipeManager.Distillery.findRecipeUsingIngredient(new ItemStack(Items.diamond))); + RecipeManager.RitesAndRituals.remove((byte) 1); + RecipeManager.Infusions.remove(RecipeManager.Infusions.getInfusion(3)); + for (Prediction H : RecipeManager.Predictions.getPredictions().values()) { + RecipeManager.Predictions.remove(H); + } + RecipeManager.CreaturePowers.remove(RecipeManager.CreaturePowers.getCreaturePower(18)); + return true; + } } diff --git a/src/main/java/alkalus/main/api/plugin/base/BasePluginWitchery.java b/src/main/java/alkalus/main/api/plugin/base/BasePluginWitchery.java index 022d9ce..4a1dae2 100644 --- a/src/main/java/alkalus/main/api/plugin/base/BasePluginWitchery.java +++ b/src/main/java/alkalus/main/api/plugin/base/BasePluginWitchery.java @@ -1,86 +1,82 @@ package alkalus.main.api.plugin.base; +import alkalus.main.api.RecipeManager; +import alkalus.main.api.plugin.interfaces.WitcheryPlugin; import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import alkalus.main.api.RecipeManager; -import alkalus.main.api.plugin.interfaces.WitcheryPlugin; - /** * This class should be extended, then the three phase methods should be {@link Override}n as required. * Constructor takes {@link LoadPhase}s, Feel free to leave {@link Override}n methods empty if they're not being use. * @author Alkalus * */ +public abstract class BasePluginWitchery implements WitcheryPlugin { + + /** Just a simple {@link Enum} containing the three main Forge load phases. + * @author Alkalus + */ + public static enum LoadPhase { + PREINIT, + INIT, + POSTINIT + } + + /** + * Small Field used to maintain validation of the plugin. + */ + private volatile boolean isValid = true; + + /** Dictates which stages your plugin will load in. + * @param initStage - Multiple {@link LoadPhase}s. Maximum 3. + */ + public BasePluginWitchery(Set phases) { + this(phases, true); + } -public abstract class BasePluginWitchery implements WitcheryPlugin { - - - /** Just a simple {@link Enum} containing the three main Forge load phases. - * @author Alkalus - */ - public static enum LoadPhase { - PREINIT, INIT, POSTINIT - } - - /** - * Small Field used to maintain validation of the plugin. - */ - private volatile boolean isValid = true; + /** Dictates which stages your plugin will load in. + * @param initStage - Multiple {@link LoadPhase}s. Maximum 3. + */ + public BasePluginWitchery(LoadPhase[] phases) { + this(new HashSet(Arrays.asList(phases)), true); + } - /** Dictates which stages your plugin will load in. - * @param initStage - Multiple {@link LoadPhase}s. Maximum 3. - */ - public BasePluginWitchery(Set phases) { - this(phases, true); - } - - /** Dictates which stages your plugin will load in. - * @param initStage - Multiple {@link LoadPhase}s. Maximum 3. - */ - public BasePluginWitchery(LoadPhase[] phases) { - this(new HashSet(Arrays.asList(phases)), true); - } - - /** - * Internal Constructor for Plugins. - * @param phases - Multiple {@link LoadPhase}s. Maximum 3. - * @param internal - {@link boolean that dictates whether or not this was an internal call. - * Please use false if you reflectively call this, for future compatibility.} - */ - private BasePluginWitchery(Set phases, boolean internal) { - if (phases == null || phases.size() <= 0 || phases.size() >= 4) { - isValid = false; - } - if (isValid) { - for (LoadPhase p : phases) { - if (p == LoadPhase.PREINIT) { - RecipeManager.PluginManager.loadPluginForPreInit(this); - } - else if (p == LoadPhase.INIT) { - RecipeManager.PluginManager.loadPluginForInit(this); - } - else if (p == LoadPhase.POSTINIT) { - RecipeManager.PluginManager.loadPluginForPostInit(this); - } - } - } - } - - /** If you wish to utilize this phase, {@link Override} the behaviour. Be sure to enable this load phase during {@link WitcheryPlugin} construction. - * @return - You should return True/False depending upon if the code completes as expected or not. - */ - public abstract boolean preInit(); + /** + * Internal Constructor for Plugins. + * @param phases - Multiple {@link LoadPhase}s. Maximum 3. + * @param internal - {@link boolean that dictates whether or not this was an internal call. + * Please use false if you reflectively call this, for future compatibility.} + */ + private BasePluginWitchery(Set phases, boolean internal) { + if (phases == null || phases.size() <= 0 || phases.size() >= 4) { + isValid = false; + } + if (isValid) { + for (LoadPhase p : phases) { + if (p == LoadPhase.PREINIT) { + RecipeManager.PluginManager.loadPluginForPreInit(this); + } else if (p == LoadPhase.INIT) { + RecipeManager.PluginManager.loadPluginForInit(this); + } else if (p == LoadPhase.POSTINIT) { + RecipeManager.PluginManager.loadPluginForPostInit(this); + } + } + } + } - /** If you wish to utilize this phase, {@link Override} the behaviour. Be sure to enable this load phase during {@link WitcheryPlugin} construction. - * @return - You should return True/False depending upon if the code completes as expected or not. - */ - public abstract boolean init(); + /** If you wish to utilize this phase, {@link Override} the behaviour. Be sure to enable this load phase during {@link WitcheryPlugin} construction. + * @return - You should return True/False depending upon if the code completes as expected or not. + */ + public abstract boolean preInit(); - /** If you wish to utilize this phase, {@link Override} the behaviour. Be sure to enable this load phase during {@link WitcheryPlugin} construction. - * @return - You should return True/False depending upon if the code completes as expected or not. - */ - public abstract boolean postInit(); + /** If you wish to utilize this phase, {@link Override} the behaviour. Be sure to enable this load phase during {@link WitcheryPlugin} construction. + * @return - You should return True/False depending upon if the code completes as expected or not. + */ + public abstract boolean init(); + /** If you wish to utilize this phase, {@link Override} the behaviour. Be sure to enable this load phase during {@link WitcheryPlugin} construction. + * @return - You should return True/False depending upon if the code completes as expected or not. + */ + public abstract boolean postInit(); } diff --git a/src/main/java/alkalus/main/api/plugin/interfaces/WitcheryPlugin.java b/src/main/java/alkalus/main/api/plugin/interfaces/WitcheryPlugin.java index f0d90f3..4ba26f4 100644 --- a/src/main/java/alkalus/main/api/plugin/interfaces/WitcheryPlugin.java +++ b/src/main/java/alkalus/main/api/plugin/interfaces/WitcheryPlugin.java @@ -2,12 +2,11 @@ public interface WitcheryPlugin { - public abstract String getPluginName(); - - public abstract boolean preInit(); - - public abstract boolean init(); - - public abstract boolean postInit(); - + public abstract String getPluginName(); + + public abstract boolean preInit(); + + public abstract boolean init(); + + public abstract boolean postInit(); } diff --git a/src/main/java/alkalus/main/asm/AsmConfig.java b/src/main/java/alkalus/main/asm/AsmConfig.java index 817b388..f98ec9e 100644 --- a/src/main/java/alkalus/main/asm/AsmConfig.java +++ b/src/main/java/alkalus/main/asm/AsmConfig.java @@ -1,190 +1,184 @@ package alkalus.main.asm; +import cpw.mods.fml.common.FMLLog; import java.io.File; import java.util.ArrayList; - -import org.apache.logging.log4j.Level; - -import cpw.mods.fml.common.FMLLog; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; +import org.apache.logging.log4j.Level; public class AsmConfig { - - public static boolean loaded; - public static Configuration config; - - public static boolean enablePatchNEI; - public static boolean allowPoppetShelfChunkLoading; - - // Predictions - public static int chancePredictionSpawnBabaYagaGood; - public static int chancePredictionSpawnBabaYagaBad; - public static int chancePredictionExtraCoal; - public static int chancePredictionSpawnEnt; - public static int chancePredictionStumbleAndFall; - public static int chancePredictionGetWet; - public static int chancePredictionExtraIron; - public static int chancePredictionSpawnZombie; - public static int chancePredictionSpawnProtectiveAnimal; - public static int chancePredictionSpawnSkeleton; - public static int chancePredictionSpawnBuriedTreasure; - public static int chancePredictionTeleportNether; - public static int chancePredictionSpawnFriendlyWolf; - public static int chancePredictionFindShinies; - public static int chancePredictionVillagerLove; - - - public AsmConfig(File file) { - if (!loaded) { - config = new Configuration(file); - syncConfig(true); - } - - } - - public static void syncConfig(boolean load) { - ArrayList propOrder = new ArrayList(); - ArrayList propOrderDebug = new ArrayList(); - try { - if (!config.isChild && load) { - config.load(); - } - Property prop; - - // Fixes NEI handling - prop = config.get("general", "enablePatchNEI", true); - prop.comment = "Patch NEI for good recipe support."; - prop.setLanguageKey("enablePatchNEI").setRequiresMcRestart(true); - enablePatchNEI = prop.getBoolean(true); - propOrder.add(prop.getName()); - - // Toggles Chunk Loading for Poppet Shelves - prop = config.get("general", "allowPoppetShelfChunkLoading", true); - prop.comment = "Enables Chunk Loading by Poppet Shelves."; - prop.setLanguageKey("allowPoppetShelfChunkLoading").setRequiresMcRestart(true); - allowPoppetShelfChunkLoading = prop.getBoolean(true); - propOrder.add(prop.getName()); - - - /* - * Predictions - */ - - // Adjusts chances for Baba Yaga spawns - prop = config.get("predictions", "chancePredictionSpawnBabaYagaGood", 2); - prop.comment = "Adjusts weight for 'Good' Baba Yaga spawns"; - prop.setLanguageKey("chancePredictionSpawnBabaYagaGood"); - chancePredictionSpawnBabaYagaGood = prop.getInt(2); - propOrder.add(prop.getName()); - - prop = config.get("predictions", "chancePredictionSpawnBabaYagaBad", 2); - prop.comment = "Adjusts weight for 'Bad' Baba Yaga spawns"; - prop.setLanguageKey("chancePredictionSpawnBabaYagaBad"); - chancePredictionSpawnBabaYagaBad = prop.getInt(2); - propOrder.add(prop.getName()); - - // Extra coal - prop = config.get("predictions", "chancePredictionExtraCoal", 13); - prop.comment = "Adjusts weight for Extra Coal Drops"; - prop.setLanguageKey("chancePredictionExtraCoal"); - chancePredictionExtraCoal = prop.getInt(13); - propOrder.add(prop.getName()); - - // Spawn Ent - prop = config.get("predictions", "chancePredictionSpawnEnt", 3); - prop.comment = "Adjusts weight for Ent Spawn"; - prop.setLanguageKey("chancePredictionSpawnEnt"); - chancePredictionSpawnEnt = prop.getInt(3); - propOrder.add(prop.getName()); - - // Create Pit - prop = config.get("predictions", "chancePredictionStumbleAndFall", 13); - prop.comment = "Adjusts weight for 'Stumble & Fall'"; - prop.setLanguageKey("chancePredictionStumbleAndFall"); - chancePredictionStumbleAndFall = prop.getInt(13); - propOrder.add(prop.getName()); - - // Get Wet - prop = config.get("predictions", "chancePredictionGetWet", 13); - prop.comment = "Adjusts weight for 'Get Wet'"; - prop.setLanguageKey("chancePredictionGetWet"); - chancePredictionGetWet = prop.getInt(13); - propOrder.add(prop.getName()); - - // Extra Iron - prop = config.get("predictions", "chancePredictionExtraIron", 8); - prop.comment = "Adjusts weight for Extra Iron Drops"; - prop.setLanguageKey("chancePredictionExtraIron"); - chancePredictionExtraIron = prop.getInt(8); - propOrder.add(prop.getName()); - - // Spawn Zombie - prop = config.get("predictions", "chancePredictionSpawnZombie", 13); - prop.comment = "Adjusts weight for Zombie Spawn"; - prop.setLanguageKey("chancePredictionSpawnZombie"); - chancePredictionSpawnZombie = prop.getInt(13); - propOrder.add(prop.getName()); - - // Spawn Wolf/Owl Friend - prop = config.get("predictions", "chancePredictionSpawnProtectiveAnimal", 13); - prop.comment = "Adjusts weight for Friendly Animal Spawn"; - prop.setLanguageKey("chancePredictionSpawnProtectiveAnimal"); - chancePredictionSpawnProtectiveAnimal = prop.getInt(13); - propOrder.add(prop.getName()); - - // Spawn Skeleton - prop = config.get("predictions", "chancePredictionSpawnSkeleton", 13); - prop.comment = "Adjusts weight for Skeleton Spawn"; - prop.setLanguageKey("chancePredictionSpawnSkeleton"); - chancePredictionSpawnSkeleton = prop.getInt(13); - propOrder.add(prop.getName()); - - // Spawn Treasure - prop = config.get("predictions", "chancePredictionSpawnBuriedTreasure", 2); - prop.comment = "Adjusts weight for Buried Treasure spawn"; - prop.setLanguageKey("chancePredictionSpawnBuriedTreasure"); - chancePredictionSpawnBuriedTreasure = prop.getInt(2); - propOrder.add(prop.getName()); - - // Nether Teleport - prop = config.get("predictions", "chancePredictionTeleportNether", 3); - prop.comment = "Adjusts weight for Nether Teleport"; - prop.setLanguageKey("chancePredictionTeleportNether"); - chancePredictionTeleportNether = prop.getInt(3); - propOrder.add(prop.getName()); - - // Spawn Wolf Friend - prop = config.get("predictions", "chancePredictionSpawnFriendlyWolf", 3); - prop.comment = "Adjusts weight for "; - prop.setLanguageKey("chancePredictionSpawnFriendlyWolf"); - chancePredictionSpawnFriendlyWolf = prop.getInt(3); - propOrder.add(prop.getName()); - - // Find Shinies (Emerald/Diamond) - prop = config.get("predictions", "chancePredictionFindShinies", 3); - prop.comment = "Adjusts weight for Bonus Diamond/Emerald drop from stone"; - prop.setLanguageKey("chancePredictionFindShinies"); - chancePredictionFindShinies = prop.getInt(3); - propOrder.add(prop.getName()); - - // Villager Love - prop = config.get("predictions", "chancePredictionVillagerLove", 2); - prop.comment = "Adjusts weight for Villager + Player lovemaking event"; - prop.setLanguageKey("chancePredictionVillagerLove"); - chancePredictionVillagerLove = prop.getInt(2); - propOrder.add(prop.getName()); - - config.setCategoryPropertyOrder("general", propOrder); - config.setCategoryPropertyOrder("predictions", propOrder); - config.setCategoryPropertyOrder("debug", propOrderDebug); - if (config.hasChanged()) { - config.save(); - } - - } catch (Exception var3) { - FMLLog.log(Level.ERROR, var3, "Witchery++ ASM had a problem loading it's config", new Object[0]); - } - - } -} \ No newline at end of file + + public static boolean loaded; + public static Configuration config; + + public static boolean enablePatchNEI; + public static boolean allowPoppetShelfChunkLoading; + + // Predictions + public static int chancePredictionSpawnBabaYagaGood; + public static int chancePredictionSpawnBabaYagaBad; + public static int chancePredictionExtraCoal; + public static int chancePredictionSpawnEnt; + public static int chancePredictionStumbleAndFall; + public static int chancePredictionGetWet; + public static int chancePredictionExtraIron; + public static int chancePredictionSpawnZombie; + public static int chancePredictionSpawnProtectiveAnimal; + public static int chancePredictionSpawnSkeleton; + public static int chancePredictionSpawnBuriedTreasure; + public static int chancePredictionTeleportNether; + public static int chancePredictionSpawnFriendlyWolf; + public static int chancePredictionFindShinies; + public static int chancePredictionVillagerLove; + + public AsmConfig(File file) { + if (!loaded) { + config = new Configuration(file); + syncConfig(true); + } + } + + public static void syncConfig(boolean load) { + ArrayList propOrder = new ArrayList(); + ArrayList propOrderDebug = new ArrayList(); + try { + if (!config.isChild && load) { + config.load(); + } + Property prop; + + // Fixes NEI handling + prop = config.get("general", "enablePatchNEI", true); + prop.comment = "Patch NEI for good recipe support."; + prop.setLanguageKey("enablePatchNEI").setRequiresMcRestart(true); + enablePatchNEI = prop.getBoolean(true); + propOrder.add(prop.getName()); + + // Toggles Chunk Loading for Poppet Shelves + prop = config.get("general", "allowPoppetShelfChunkLoading", true); + prop.comment = "Enables Chunk Loading by Poppet Shelves."; + prop.setLanguageKey("allowPoppetShelfChunkLoading").setRequiresMcRestart(true); + allowPoppetShelfChunkLoading = prop.getBoolean(true); + propOrder.add(prop.getName()); + + /* + * Predictions + */ + + // Adjusts chances for Baba Yaga spawns + prop = config.get("predictions", "chancePredictionSpawnBabaYagaGood", 2); + prop.comment = "Adjusts weight for 'Good' Baba Yaga spawns"; + prop.setLanguageKey("chancePredictionSpawnBabaYagaGood"); + chancePredictionSpawnBabaYagaGood = prop.getInt(2); + propOrder.add(prop.getName()); + + prop = config.get("predictions", "chancePredictionSpawnBabaYagaBad", 2); + prop.comment = "Adjusts weight for 'Bad' Baba Yaga spawns"; + prop.setLanguageKey("chancePredictionSpawnBabaYagaBad"); + chancePredictionSpawnBabaYagaBad = prop.getInt(2); + propOrder.add(prop.getName()); + + // Extra coal + prop = config.get("predictions", "chancePredictionExtraCoal", 13); + prop.comment = "Adjusts weight for Extra Coal Drops"; + prop.setLanguageKey("chancePredictionExtraCoal"); + chancePredictionExtraCoal = prop.getInt(13); + propOrder.add(prop.getName()); + + // Spawn Ent + prop = config.get("predictions", "chancePredictionSpawnEnt", 3); + prop.comment = "Adjusts weight for Ent Spawn"; + prop.setLanguageKey("chancePredictionSpawnEnt"); + chancePredictionSpawnEnt = prop.getInt(3); + propOrder.add(prop.getName()); + + // Create Pit + prop = config.get("predictions", "chancePredictionStumbleAndFall", 13); + prop.comment = "Adjusts weight for 'Stumble & Fall'"; + prop.setLanguageKey("chancePredictionStumbleAndFall"); + chancePredictionStumbleAndFall = prop.getInt(13); + propOrder.add(prop.getName()); + + // Get Wet + prop = config.get("predictions", "chancePredictionGetWet", 13); + prop.comment = "Adjusts weight for 'Get Wet'"; + prop.setLanguageKey("chancePredictionGetWet"); + chancePredictionGetWet = prop.getInt(13); + propOrder.add(prop.getName()); + + // Extra Iron + prop = config.get("predictions", "chancePredictionExtraIron", 8); + prop.comment = "Adjusts weight for Extra Iron Drops"; + prop.setLanguageKey("chancePredictionExtraIron"); + chancePredictionExtraIron = prop.getInt(8); + propOrder.add(prop.getName()); + + // Spawn Zombie + prop = config.get("predictions", "chancePredictionSpawnZombie", 13); + prop.comment = "Adjusts weight for Zombie Spawn"; + prop.setLanguageKey("chancePredictionSpawnZombie"); + chancePredictionSpawnZombie = prop.getInt(13); + propOrder.add(prop.getName()); + + // Spawn Wolf/Owl Friend + prop = config.get("predictions", "chancePredictionSpawnProtectiveAnimal", 13); + prop.comment = "Adjusts weight for Friendly Animal Spawn"; + prop.setLanguageKey("chancePredictionSpawnProtectiveAnimal"); + chancePredictionSpawnProtectiveAnimal = prop.getInt(13); + propOrder.add(prop.getName()); + + // Spawn Skeleton + prop = config.get("predictions", "chancePredictionSpawnSkeleton", 13); + prop.comment = "Adjusts weight for Skeleton Spawn"; + prop.setLanguageKey("chancePredictionSpawnSkeleton"); + chancePredictionSpawnSkeleton = prop.getInt(13); + propOrder.add(prop.getName()); + + // Spawn Treasure + prop = config.get("predictions", "chancePredictionSpawnBuriedTreasure", 2); + prop.comment = "Adjusts weight for Buried Treasure spawn"; + prop.setLanguageKey("chancePredictionSpawnBuriedTreasure"); + chancePredictionSpawnBuriedTreasure = prop.getInt(2); + propOrder.add(prop.getName()); + + // Nether Teleport + prop = config.get("predictions", "chancePredictionTeleportNether", 3); + prop.comment = "Adjusts weight for Nether Teleport"; + prop.setLanguageKey("chancePredictionTeleportNether"); + chancePredictionTeleportNether = prop.getInt(3); + propOrder.add(prop.getName()); + + // Spawn Wolf Friend + prop = config.get("predictions", "chancePredictionSpawnFriendlyWolf", 3); + prop.comment = "Adjusts weight for "; + prop.setLanguageKey("chancePredictionSpawnFriendlyWolf"); + chancePredictionSpawnFriendlyWolf = prop.getInt(3); + propOrder.add(prop.getName()); + + // Find Shinies (Emerald/Diamond) + prop = config.get("predictions", "chancePredictionFindShinies", 3); + prop.comment = "Adjusts weight for Bonus Diamond/Emerald drop from stone"; + prop.setLanguageKey("chancePredictionFindShinies"); + chancePredictionFindShinies = prop.getInt(3); + propOrder.add(prop.getName()); + + // Villager Love + prop = config.get("predictions", "chancePredictionVillagerLove", 2); + prop.comment = "Adjusts weight for Villager + Player lovemaking event"; + prop.setLanguageKey("chancePredictionVillagerLove"); + chancePredictionVillagerLove = prop.getInt(2); + propOrder.add(prop.getName()); + + config.setCategoryPropertyOrder("general", propOrder); + config.setCategoryPropertyOrder("predictions", propOrder); + config.setCategoryPropertyOrder("debug", propOrderDebug); + if (config.hasChanged()) { + config.save(); + } + + } catch (Exception var3) { + FMLLog.log(Level.ERROR, var3, "Witchery++ ASM had a problem loading it's config", new Object[0]); + } + } +} diff --git a/src/main/java/alkalus/main/asm/AsmUtils.java b/src/main/java/alkalus/main/asm/AsmUtils.java index 77731a5..ec54b5a 100644 --- a/src/main/java/alkalus/main/asm/AsmUtils.java +++ b/src/main/java/alkalus/main/asm/AsmUtils.java @@ -1,34 +1,30 @@ package alkalus.main.asm; +import alkalus.main.core.util.Logger; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; - import org.apache.commons.io.IOUtils; -import alkalus.main.core.util.Logger; - public class AsmUtils { - public static byte[] getClassBytes(String aFullClassName) { - String aResourcePath = aFullClassName.replace('.', '/'); - Logger.ASM("Trying to get class byte[] for: "+aFullClassName); - Logger.ASM("Using resource path: "+aResourcePath); - byte[] aData = null; - try { - aData = Files.readAllBytes(Paths.get(AsmUtils.class.getClassLoader().getResource(aResourcePath).toURI())); - } - catch (IOException | URISyntaxException e) { - e.printStackTrace(); - try { - aData = IOUtils.toByteArray(AsmUtils.class.getClassLoader().getResourceAsStream(aResourcePath)); - } - catch (IOException r) { - r.printStackTrace(); - } - } - return aData; - } - + public static byte[] getClassBytes(String aFullClassName) { + String aResourcePath = aFullClassName.replace('.', '/'); + Logger.ASM("Trying to get class byte[] for: " + aFullClassName); + Logger.ASM("Using resource path: " + aResourcePath); + byte[] aData = null; + try { + aData = Files.readAllBytes(Paths.get( + AsmUtils.class.getClassLoader().getResource(aResourcePath).toURI())); + } catch (IOException | URISyntaxException e) { + e.printStackTrace(); + try { + aData = IOUtils.toByteArray(AsmUtils.class.getClassLoader().getResourceAsStream(aResourcePath)); + } catch (IOException r) { + r.printStackTrace(); + } + } + return aData; + } } diff --git a/src/main/java/alkalus/main/asm/WE_CORE.java b/src/main/java/alkalus/main/asm/WE_CORE.java index 9a7151a..5f7752d 100644 --- a/src/main/java/alkalus/main/asm/WE_CORE.java +++ b/src/main/java/alkalus/main/asm/WE_CORE.java @@ -5,8 +5,8 @@ import java.util.List; public class WE_CORE { - public static final String NAME = "WitcheryExtras_ASM"; - public static final String MODID = "WitcheryExtras_ASM"; - public static final String VERSION = "0.1-Beta"; - public static List DEPENDENCIES = new ArrayList<>(Arrays.asList(new String[] {"required-before:witchery;"})); + public static final String NAME = "WitcheryExtras_ASM"; + public static final String MODID = "WitcheryExtras_ASM"; + public static final String VERSION = "0.1-Beta"; + public static List DEPENDENCIES = new ArrayList<>(Arrays.asList(new String[] {"required-before:witchery;"})); } diff --git a/src/main/java/alkalus/main/asm/WE_CORE_Container.java b/src/main/java/alkalus/main/asm/WE_CORE_Container.java index a0200bc..9c1f427 100644 --- a/src/main/java/alkalus/main/asm/WE_CORE_Container.java +++ b/src/main/java/alkalus/main/asm/WE_CORE_Container.java @@ -1,13 +1,9 @@ package alkalus.main.asm; -import java.util.Arrays; -import java.util.List; - -import com.google.common.eventbus.EventBus; -import com.google.common.eventbus.Subscribe; - import alkalus.main.core.util.Logger; import alkalus.main.core.util.ReflectionUtils; +import com.google.common.eventbus.EventBus; +import com.google.common.eventbus.Subscribe; import cpw.mods.fml.common.DummyModContainer; import cpw.mods.fml.common.LoadController; import cpw.mods.fml.common.Mod.EventHandler; @@ -17,59 +13,56 @@ import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.versioning.ArtifactVersion; +import java.util.Arrays; +import java.util.List; public class WE_CORE_Container extends DummyModContainer { - public WE_CORE_Container() { + public WE_CORE_Container() { - super(new ModMetadata()); - ModMetadata meta = getMetadata(); - meta.modId = WE_CORE.MODID; - meta.name = WE_CORE.NAME; - meta.version = WE_CORE.VERSION; - meta.credits = "Roll Credits ..."; - meta.authorList = Arrays.asList("Alkalus"); - meta.description = ""; - meta.url = ""; - meta.updateUrl = ""; - meta.screenshots = new String[0]; - meta.logoFile = ""; - meta.dependencies = (List) WE_CORE.DEPENDENCIES; + super(new ModMetadata()); + ModMetadata meta = getMetadata(); + meta.modId = WE_CORE.MODID; + meta.name = WE_CORE.NAME; + meta.version = WE_CORE.VERSION; + meta.credits = "Roll Credits ..."; + meta.authorList = Arrays.asList("Alkalus"); + meta.description = ""; + meta.url = ""; + meta.updateUrl = ""; + meta.screenshots = new String[0]; + meta.logoFile = ""; + meta.dependencies = (List) WE_CORE.DEPENDENCIES; + } - } - - @Override - public boolean registerBus(EventBus bus, LoadController controller) { - bus.register(this); - return true; - } + @Override + public boolean registerBus(EventBus bus, LoadController controller) { + bus.register(this); + return true; + } - @Subscribe - public void modConstruction(FMLConstructionEvent evt){ + @Subscribe + public void modConstruction(FMLConstructionEvent evt) {} - } + @Subscribe + public void init(FMLInitializationEvent evt) {} - @Subscribe - public void init(FMLInitializationEvent evt) { + @EventHandler + public void load(final FMLInitializationEvent e) { + Logger.ASM("Begin resource allocation for " + WE_CORE.MODID + " V" + WE_CORE.VERSION); + } - } - - @EventHandler - public void load(final FMLInitializationEvent e) { - Logger.ASM("Begin resource allocation for " + WE_CORE.MODID + " V" + WE_CORE.VERSION); - } - - @Subscribe - public void preInit(FMLPreInitializationEvent event) { - Logger.ASM("Loading " + WE_CORE.MODID + " V" + WE_CORE.VERSION); - if (AsmConfig.enablePatchNEI) { - // Pre-load this class so it can be transformed into an empty class. Fixes NEI catching and registering it. - ReflectionUtils.doesClassExist("com.emoniph.witchery.integration.NEIWitcheryConfig"); - } - } + @Subscribe + public void preInit(FMLPreInitializationEvent event) { + Logger.ASM("Loading " + WE_CORE.MODID + " V" + WE_CORE.VERSION); + if (AsmConfig.enablePatchNEI) { + // Pre-load this class so it can be transformed into an empty class. Fixes NEI catching and registering it. + ReflectionUtils.doesClassExist("com.emoniph.witchery.integration.NEIWitcheryConfig"); + } + } - @Subscribe - public void postInit(FMLPostInitializationEvent evt) { - Logger.ASM("Finished loading Witchery++ Pre-Loader."); - } -} \ No newline at end of file + @Subscribe + public void postInit(FMLPostInitializationEvent evt) { + Logger.ASM("Finished loading Witchery++ Pre-Loader."); + } +} diff --git a/src/main/java/alkalus/main/asm/WE_CORE_FMLLoadingPlugin.java b/src/main/java/alkalus/main/asm/WE_CORE_FMLLoadingPlugin.java index 65a0a55..d7d24a6 100644 --- a/src/main/java/alkalus/main/asm/WE_CORE_FMLLoadingPlugin.java +++ b/src/main/java/alkalus/main/asm/WE_CORE_FMLLoadingPlugin.java @@ -1,40 +1,36 @@ package alkalus.main.asm; -import java.util.Map; - import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.SortingIndex; +import java.util.Map; -@SortingIndex(10097) +@SortingIndex(10097) @MCVersion(value = "1.7.10") -public class WE_CORE_FMLLoadingPlugin implements IFMLLoadingPlugin { - - //-Dfml.coreMods.load=alkalus.main.asm.WE_CORE_FMLLoadingPlugin - - @Override - public String getAccessTransformerClass() { - return null; - } +public class WE_CORE_FMLLoadingPlugin implements IFMLLoadingPlugin { - @Override - public String[] getASMTransformerClass() { - return new String[]{WE_CORE_Handler.class.getName()}; - } + // -Dfml.coreMods.load=alkalus.main.asm.WE_CORE_FMLLoadingPlugin - @Override - public String getModContainerClass() { - return WE_CORE_Container.class.getName(); - } + @Override + public String getAccessTransformerClass() { + return null; + } - @Override - public String getSetupClass() { - return null; - } + @Override + public String[] getASMTransformerClass() { + return new String[] {WE_CORE_Handler.class.getName()}; + } - @Override - public void injectData(Map data) { + @Override + public String getModContainerClass() { + return WE_CORE_Container.class.getName(); + } - } + @Override + public String getSetupClass() { + return null; + } -} \ No newline at end of file + @Override + public void injectData(Map data) {} +} diff --git a/src/main/java/alkalus/main/asm/WE_CORE_Handler.java b/src/main/java/alkalus/main/asm/WE_CORE_Handler.java index 4abe78b..5dc8e6c 100644 --- a/src/main/java/alkalus/main/asm/WE_CORE_Handler.java +++ b/src/main/java/alkalus/main/asm/WE_CORE_Handler.java @@ -1,79 +1,81 @@ package alkalus.main.asm; -import java.io.File; -import java.io.IOException; - import alkalus.main.asm.transformer.ClassTransformer_Witchery_NEIWitcheryConfig; import alkalus.main.asm.transformer.ClassTransformer_Witchery_TileEntityPoppetShelf; import alkalus.main.asm.transformer.ClassTransformer_Witchery_TileEntityWitchesOven; -import alkalus.main.core.util.Logger; import cpw.mods.fml.relauncher.CoreModManager; import cpw.mods.fml.relauncher.ReflectionHelper; +import java.io.File; +import java.io.IOException; import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.Launch; @SuppressWarnings("static-access") public class WE_CORE_Handler implements IClassTransformer { - - public static final AsmConfig mConfig; + public static final AsmConfig mConfig; + + static { + mConfig = new AsmConfig(new File("config/WitcheryExtras/asm.cfg")); + System.out.println("[Witchery++][ASM] Asm Config Location: " + + mConfig.config.getConfigFile().getAbsolutePath()); + } + + private static Boolean mObf = null; + + public boolean checkObfuscated() { + if (mObf != null) { + return mObf; + } + boolean obfuscated = false; + try { + obfuscated = !(boolean) ReflectionHelper.findField(CoreModManager.class, "deobfuscatedEnvironment") + .get(null); + } catch (IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + byte[] bs; + try { + bs = Launch.classLoader.getClassBytes("net.minecraft.world.World"); + if (bs != null) { + obfuscated = false; + } else { + obfuscated = true; + } + } catch (IOException e1) { + e1.printStackTrace(); + obfuscated = false; + } + } + mObf = obfuscated; + return obfuscated; + } + + public byte[] transform(String name, String transformedName, byte[] basicClass) { + // Is this environment obfuscated? (Extra checks just in case some weird shit happens during the check) + boolean obfuscated = checkObfuscated(); - static { - mConfig = new AsmConfig(new File("config/WitcheryExtras/asm.cfg")); - System.out.println("[Witchery++][ASM] Asm Config Location: "+mConfig.config.getConfigFile().getAbsolutePath()); - } - - private static Boolean mObf = null; - - public boolean checkObfuscated() { - if (mObf != null) { - return mObf; - } - boolean obfuscated = false; - try { - obfuscated = !(boolean) ReflectionHelper.findField(CoreModManager.class, "deobfuscatedEnvironment").get(null); - } catch (IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - byte[] bs; - try { - bs = Launch.classLoader.getClassBytes("net.minecraft.world.World"); - if (bs != null) { - obfuscated = false; - } else { - obfuscated = true; - } - } catch (IOException e1) { - e1.printStackTrace(); - obfuscated = false; - } - } - mObf = obfuscated; - return obfuscated; - } + // Fix Bad NEI Handling, by patching it out entirely. + if (transformedName.equals("com.emoniph.witchery.integration.NEIWitcheryConfig") && mConfig.enablePatchNEI) { + return new ClassTransformer_Witchery_NEIWitcheryConfig(transformedName, basicClass, obfuscated) + .getWriter() + .toByteArray(); + // return AsmUtils.getClassBytes("com.emoniph.witchery.integration.NEIWitcheryConfig"); + } - public byte[] transform(String name, String transformedName, byte[] basicClass) { - // Is this environment obfuscated? (Extra checks just in case some weird shit happens during the check) - boolean obfuscated = checkObfuscated(); + // Patch witches oven to support recipe maps. + if (transformedName.equals("com.emoniph.witchery.blocks.BlockWitchesOven$TileEntityWitchesOven")) { + return new ClassTransformer_Witchery_TileEntityWitchesOven(transformedName, basicClass, obfuscated) + .getWriter() + .toByteArray(); + } - // Fix Bad NEI Handling, by patching it out entirely. - if (transformedName.equals("com.emoniph.witchery.integration.NEIWitcheryConfig") && mConfig.enablePatchNEI) { - return new ClassTransformer_Witchery_NEIWitcheryConfig(transformedName, basicClass, obfuscated).getWriter().toByteArray(); - //return AsmUtils.getClassBytes("com.emoniph.witchery.integration.NEIWitcheryConfig"); - } - - // Patch witches oven to support recipe maps. - if (transformedName.equals("com.emoniph.witchery.blocks.BlockWitchesOven$TileEntityWitchesOven")) { - return new ClassTransformer_Witchery_TileEntityWitchesOven(transformedName, basicClass, obfuscated).getWriter().toByteArray(); - } - - // Patch Poppet Shelf to enable/disable chunk loading - if (transformedName.equals("com.emoniph.witchery.blocks.BlockPoppetShelf$TileEntityPoppetShelf")) { - return new ClassTransformer_Witchery_TileEntityPoppetShelf(transformedName, basicClass, obfuscated).getWriter().toByteArray(); - } - - return basicClass; - } + // Patch Poppet Shelf to enable/disable chunk loading + if (transformedName.equals("com.emoniph.witchery.blocks.BlockPoppetShelf$TileEntityPoppetShelf")) { + return new ClassTransformer_Witchery_TileEntityPoppetShelf(transformedName, basicClass, obfuscated) + .getWriter() + .toByteArray(); + } - - + return basicClass; + } } diff --git a/src/main/java/alkalus/main/asm/transformer/BaseTransformer.java b/src/main/java/alkalus/main/asm/transformer/BaseTransformer.java index c9db825..24ee35d 100644 --- a/src/main/java/alkalus/main/asm/transformer/BaseTransformer.java +++ b/src/main/java/alkalus/main/asm/transformer/BaseTransformer.java @@ -2,119 +2,116 @@ import static org.objectweb.asm.Opcodes.*; +import cpw.mods.fml.relauncher.FMLRelaunchLog; import org.apache.logging.log4j.Level; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; -import cpw.mods.fml.relauncher.FMLRelaunchLog; - public abstract class BaseTransformer { - protected final boolean mObf; - protected boolean isValid = false; - private final ClassReader reader; - private final ClassWriter writer; - - public BaseTransformer(String transformedName, byte[] basicClass, boolean isObf) { - ClassReader aTempReader = null; - ClassWriter aTempWriter = null; - mObf = isObf; - log("Transforming "+transformedName); - aTempReader = new ClassReader(basicClass); - aTempWriter = new ClassWriter(aTempReader, ClassWriter.COMPUTE_FRAMES); - reader = aTempReader; - writer = aTempWriter; - } - - protected final void init() { - reader.accept(new MethodAdaptor(writer), 0); - if (runInjectorMultipleTimes()) { - for (String methodName : getMethodNamesToStrip()) { - injectMethod(methodName, writer); - } - } - else { - injectMethod("NONE", writer); - } - if (reader != null && writer != null) { - isValid = true; - } else { - isValid = false; - } - log("Valid? " + isValid + "."); - } - - protected abstract boolean runInjectorMultipleTimes(); - - public final boolean isValidTransformer() { - return isValid; - } - - public final ClassReader getReader() { - return reader; - } - - public final ClassWriter getWriter() { - return writer; - } - - public abstract boolean injectMethod(String aMethodName, ClassWriter cw); - - public abstract String[] getMethodNamesToStrip(); - - public abstract String[] getMethodDescriptorsToStrip(); - - public abstract String getTransformerName(); - - protected void log(String s) { - FMLRelaunchLog.log("[Witchery++ ASM] "+getTransformerName(), Level.INFO, s); - } - - public class MethodAdaptor extends ClassVisitor { - - public MethodAdaptor(ClassVisitor cv) { - super(ASM5, cv); - this.cv = cv; - } - - - @Override - public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - MethodVisitor methodVisitor; - boolean found = false; - String[] aNames = getMethodNamesToStrip(); - String[] aDesc = getMethodDescriptorsToStrip(); - boolean checkDesc = aDesc != null && aDesc.length > 0; - - for (int i=0;i 0; + + for (int i = 0; i < getMethodNamesToStrip().length; i++) { + if (checkDesc) { + if (desc.equals(aDesc[i])) { + if (name.equals(aNames[i])) { + found = true; + break; + } + } + } else { + if (name.equals(aNames[i])) { + found = true; + break; + } + } + } + if (!found) { + methodVisitor = super.visitMethod(access, name, desc, signature, exceptions); + } else { + methodVisitor = null; + } + if (found) { + log("Found method " + name + ", removing. " + + (checkDesc + ? "Using matching method desc. '" + checkDesc + "'" + : "Did not compare method desc.")); + } + return methodVisitor; + } + } } diff --git a/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_NEIWitcheryConfig.java b/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_NEIWitcheryConfig.java index fcab67f..c0740a1 100644 --- a/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_NEIWitcheryConfig.java +++ b/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_NEIWitcheryConfig.java @@ -7,71 +7,68 @@ public class ClassTransformer_Witchery_NEIWitcheryConfig extends BaseTransformer { - private boolean didLoadDummy = false; - - public ClassTransformer_Witchery_NEIWitcheryConfig(String transformedName, byte[] basicClass, boolean isObf) { - super(transformedName, basicClass, isObf); - getReader().accept(new InterfaceAdaptor(getWriter()), 0); - if (!didLoadDummy) { - init(); - } - } + private boolean didLoadDummy = false; - public boolean injectMethod(String aMethodName, ClassWriter cw) { - log("Patching Success."); - return true; - } + public ClassTransformer_Witchery_NEIWitcheryConfig(String transformedName, byte[] basicClass, boolean isObf) { + super(transformedName, basicClass, isObf); + getReader().accept(new InterfaceAdaptor(getWriter()), 0); + if (!didLoadDummy) { + init(); + } + } - @Override - public String[] getMethodNamesToStrip() { - return new String[] { - "loadConfig", - }; - } + public boolean injectMethod(String aMethodName, ClassWriter cw) { + log("Patching Success."); + return true; + } - @Override - public String[] getMethodDescriptorsToStrip() { - return null; - } + @Override + public String[] getMethodNamesToStrip() { + return new String[] { + "loadConfig", + }; + } - @Override - public String getTransformerName() { - return "NEI Fix"; - } + @Override + public String[] getMethodDescriptorsToStrip() { + return null; + } - @Override - protected boolean runInjectorMultipleTimes() { - return false; - } - - public class InterfaceAdaptor extends ClassVisitor { - - public InterfaceAdaptor(ClassVisitor cv) { - super(ASM5, cv); - this.cv = cv; - } + @Override + public String getTransformerName() { + return "NEI Fix"; + } + @Override + protected boolean runInjectorMultipleTimes() { + return false; + } - @Override - public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { - if (interfaces != null && interfaces.length > 0) { - String[] aNewInterfaces = new String[interfaces.length > 1 ? interfaces.length-1 : 1]; - int aIndex = 0; - for (String s : interfaces) { - if (!s.contains("IConfigureNEI")) { - aNewInterfaces[aIndex++] = s; - } - else { - log("Found Interface "+s+" | Removing"); - } - } - } - else if (interfaces == null || interfaces.length == 0) { - log("Found 0 Interfaces | Dummy Class Load success."); - didLoadDummy = true; - } - super.visit(version, access, name, signature, superName, interfaces); - } - } + public class InterfaceAdaptor extends ClassVisitor { + public InterfaceAdaptor(ClassVisitor cv) { + super(ASM5, cv); + this.cv = cv; + } + + @Override + public void visit( + int version, int access, String name, String signature, String superName, String[] interfaces) { + if (interfaces != null && interfaces.length > 0) { + String[] aNewInterfaces = new String[interfaces.length > 1 ? interfaces.length - 1 : 1]; + int aIndex = 0; + for (String s : interfaces) { + if (!s.contains("IConfigureNEI")) { + aNewInterfaces[aIndex++] = s; + } else { + log("Found Interface " + s + " | Removing"); + } + } + } else if (interfaces == null || interfaces.length == 0) { + log("Found 0 Interfaces | Dummy Class Load success."); + didLoadDummy = true; + } + super.visit(version, access, name, signature, superName, interfaces); + } + } } diff --git a/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityPoppetShelf.java b/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityPoppetShelf.java index c4185dd..167a847 100644 --- a/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityPoppetShelf.java +++ b/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityPoppetShelf.java @@ -13,110 +13,114 @@ public class ClassTransformer_Witchery_TileEntityPoppetShelf extends BaseTransformer { - public ClassTransformer_Witchery_TileEntityPoppetShelf(String transformedName, byte[] basicClass, boolean isObf) { - super(transformedName, basicClass, isObf); - init(); - } - - public boolean injectMethod(String aMethodName, ClassWriter cw) { - boolean[] aResults = new boolean[2]; - aResults[0] = inject_initiate(); - aResults[1] = inject_invalidate(); - for (boolean b : aResults) { - if (!b) { - log("Patching failed."); - return false; - } - } - log("Patching Success."); - return true; - } - - //com.emoniph.witchery.blocks.BlockPoppetShelf.TileEntityPoppetShelf - - private boolean inject_initiate() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PROTECTED, "initiate", "()V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(138, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, "com/emoniph/witchery/blocks/TileEntityBase", "initiate", "()V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(139, l1); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/PoppetShelfUtils", "initiate", "(Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;)V", false); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLineNumber(140, l2); - mv.visitInsn(RETURN); - Label l3 = new Label(); - mv.visitLabel(l3); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;", null, l0, l3, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - return true; - } - - private boolean inject_invalidate() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PUBLIC, "invalidate", "()V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(155, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/PoppetShelfUtils", "invalidate", "(Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;)V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(156, l1); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESPECIAL, "com/emoniph/witchery/blocks/TileEntityBase", "invalidate", "()V", false); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLineNumber(157, l2); - mv.visitInsn(RETURN); - Label l3 = new Label(); - mv.visitLabel(l3); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;", null, l0, l3, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - return true; - } - - - - - - - - @Override - public String[] getMethodNamesToStrip() { - return new String[] { - "initiate", - "invalidate", - }; - } - - @Override - public String[] getMethodDescriptorsToStrip() { - return null; - } - - @Override - public String getTransformerName() { - return "Poppet Shelf Chunkloading"; - } - - @Override - protected boolean runInjectorMultipleTimes() { - return false; - } - + public ClassTransformer_Witchery_TileEntityPoppetShelf(String transformedName, byte[] basicClass, boolean isObf) { + super(transformedName, basicClass, isObf); + init(); + } + + public boolean injectMethod(String aMethodName, ClassWriter cw) { + boolean[] aResults = new boolean[2]; + aResults[0] = inject_initiate(); + aResults[1] = inject_invalidate(); + for (boolean b : aResults) { + if (!b) { + log("Patching failed."); + return false; + } + } + log("Patching Success."); + return true; + } + + // com.emoniph.witchery.blocks.BlockPoppetShelf.TileEntityPoppetShelf + + private boolean inject_initiate() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PROTECTED, "initiate", "()V", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(138, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn(INVOKESPECIAL, "com/emoniph/witchery/blocks/TileEntityBase", "initiate", "()V", false); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLineNumber(139, l1); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/PoppetShelfUtils", + "initiate", + "(Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;)V", + false); + Label l2 = new Label(); + mv.visitLabel(l2); + mv.visitLineNumber(140, l2); + mv.visitInsn(RETURN); + Label l3 = new Label(); + mv.visitLabel(l3); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;", null, l0, l3, 0); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + return true; + } + + private boolean inject_invalidate() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PUBLIC, "invalidate", "()V", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(155, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/PoppetShelfUtils", + "invalidate", + "(Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;)V", + false); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLineNumber(156, l1); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn(INVOKESPECIAL, "com/emoniph/witchery/blocks/TileEntityBase", "invalidate", "()V", false); + Label l2 = new Label(); + mv.visitLabel(l2); + mv.visitLineNumber(157, l2); + mv.visitInsn(RETURN); + Label l3 = new Label(); + mv.visitLabel(l3); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockPoppetShelf$TileEntityPoppetShelf;", null, l0, l3, 0); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + return true; + } + + @Override + public String[] getMethodNamesToStrip() { + return new String[] { + "initiate", "invalidate", + }; + } + + @Override + public String[] getMethodDescriptorsToStrip() { + return null; + } + + @Override + public String getTransformerName() { + return "Poppet Shelf Chunkloading"; + } + + @Override + protected boolean runInjectorMultipleTimes() { + return false; + } } diff --git a/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityWitchesOven.java b/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityWitchesOven.java index d01281e..e5b486b 100644 --- a/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityWitchesOven.java +++ b/src/main/java/alkalus/main/asm/transformer/ClassTransformer_Witchery_TileEntityWitchesOven.java @@ -16,313 +16,364 @@ public class ClassTransformer_Witchery_TileEntityWitchesOven extends BaseTransformer { - private final String mItemStack; - - public ClassTransformer_Witchery_TileEntityWitchesOven(String transformedName, byte[] basicClass, boolean isObf) { - super(transformedName, basicClass, isObf); - mItemStack = mObf ? "add" : "net/minecraft/item/ItemStack"; - log("Patching Obfuscated classes? "+mObf); - init(); - } - - public boolean injectMethod(String aMethodName, ClassWriter cw) { - boolean[] aResults = new boolean[10]; - aResults[0] = inject_updateEntity(); - aResults[1] = inject_canSmelt(); - aResults[2] = inject_smeltItem(); - aResults[3] = inject_getFumeFunnels(); - aResults[4] = inject_isFumeFunnel(); - aResults[5] = inject_getFumeFunnelsChance(); - aResults[6] = inject_getFumeFunnelChance(); - aResults[7] = inject_getCookTime(); - aResults[8] = inject_generateByProduct(); - aResults[9] = inject_createByProduct(); - for (boolean b : aResults) { - if (!b) { - log("Patching failed."); - return false; - } - } - log("Patching Success."); - return true; - } - - private boolean inject_updateEntity() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PUBLIC, "updateEntity", "()V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(151, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "updateEntity", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(152, l1); - mv.visitInsn(RETURN); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - return true; - } - - private boolean inject_canSmelt() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "canSmelt", "()Z", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(155, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "canSmelt", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)Z", false); - mv.visitInsn(IRETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - return true; - } - - private boolean inject_smeltItem() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PUBLIC, "smeltItem", "()V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(159, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "smeltItem", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(160, l1); - mv.visitInsn(RETURN); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - return true; - } - - private boolean inject_getFumeFunnels() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "getFumeFunnels", "()I", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(163, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "getFumeFunnels", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)I", false); - mv.visitInsn(IRETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - return true; - } - - private boolean inject_isFumeFunnel() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "isFumeFunnel", "(IIII)Z", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(167, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ILOAD, 1); - mv.visitVarInsn(ILOAD, 2); - mv.visitVarInsn(ILOAD, 3); - mv.visitVarInsn(ILOAD, 4); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "isFumeFunnel", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;IIII)Z", false); - mv.visitInsn(IRETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); - mv.visitLocalVariable("xCoord", "I", null, l0, l1, 1); - mv.visitLocalVariable("yCoord", "I", null, l0, l1, 2); - mv.visitLocalVariable("zCoord", "I", null, l0, l1, 3); - mv.visitLocalVariable("meta", "I", null, l0, l1, 4); - mv.visitMaxs(5, 5); - mv.visitEnd(); - - return true; - } - - private boolean inject_getFumeFunnelsChance() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "getFumeFunnelsChance", "()D", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(171, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "getFumeFunnelsChance", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)D", false); - mv.visitInsn(DRETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); - mv.visitMaxs(2, 1); - mv.visitEnd(); - - return true; - } - - private boolean inject_getFumeFunnelChance() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "getFumeFunnelChance", "(IIII)D", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(175, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, "com/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven", "xCoord", "I"); - mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, "com/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven", "yCoord", "I"); - mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, "com/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven", "zCoord", "I"); - mv.visitVarInsn(ILOAD, 4); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "getFumeFunnelChance", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;IIII)D", false); - mv.visitInsn(DRETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); - mv.visitLocalVariable("x", "I", null, l0, l1, 1); - mv.visitLocalVariable("y", "I", null, l0, l1, 2); - mv.visitLocalVariable("z", "I", null, l0, l1, 3); - mv.visitLocalVariable("meta", "I", null, l0, l1, 4); - mv.visitMaxs(5, 5); - mv.visitEnd(); - - return true; - } - - private boolean inject_getCookTime() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "getCookTime", "()I", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(178, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "getCookTime", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)I", false); - mv.visitInsn(IRETURN); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); - mv.visitMaxs(1, 1); - mv.visitEnd(); - - return true; - } - - private boolean inject_generateByProduct() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "generateByProduct", "(L"+mItemStack+";)V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(182, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ALOAD, 1); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "generateByProduct", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;L"+mItemStack+";)V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(183, l1); - mv.visitInsn(RETURN); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); - mv.visitLocalVariable("itemstack", "L"+mItemStack+";", null, l0, l2, 1); - mv.visitMaxs(2, 2); - mv.visitEnd(); - - return true; - } - - private boolean inject_createByProduct() { - MethodVisitor mv; - - mv = getWriter().visitMethod(ACC_PRIVATE, "createByProduct", "(L"+mItemStack+";)V", null, null); - mv.visitCode(); - Label l0 = new Label(); - mv.visitLabel(l0); - mv.visitLineNumber(186, l0); - mv.visitVarInsn(ALOAD, 0); - mv.visitVarInsn(ALOAD, 1); - mv.visitMethodInsn(INVOKESTATIC, "alkalus/main/core/util/WitchesOvenUtils", "createByProduct", "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;L"+mItemStack+";)V", false); - Label l1 = new Label(); - mv.visitLabel(l1); - mv.visitLineNumber(187, l1); - mv.visitInsn(RETURN); - Label l2 = new Label(); - mv.visitLabel(l2); - mv.visitLocalVariable("this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); - mv.visitLocalVariable("byProduct", "L"+mItemStack+";", null, l0, l2, 1); - mv.visitMaxs(2, 2); - mv.visitEnd(); - - return true; - } - - - - - - - - - - - - - @Override - public String[] getMethodNamesToStrip() { - return new String[] { - "getCookTime", - "updateEntity", - "canSmelt", - "smeltItem", - "getFumeFunnels", - "isFumeFunnel", - "getFumeFunnelsChance", - "getFumeFunnelChance", - "getCookTime", - "generateByProduct", - "createByProduct", - }; - } - - @Override - public String[] getMethodDescriptorsToStrip() { - return null; - } - - @Override - public String getTransformerName() { - return "Witches Oven Fix"; - } - - @Override - protected boolean runInjectorMultipleTimes() { - return false; - } - + private final String mItemStack; + + public ClassTransformer_Witchery_TileEntityWitchesOven(String transformedName, byte[] basicClass, boolean isObf) { + super(transformedName, basicClass, isObf); + mItemStack = mObf ? "add" : "net/minecraft/item/ItemStack"; + log("Patching Obfuscated classes? " + mObf); + init(); + } + + public boolean injectMethod(String aMethodName, ClassWriter cw) { + boolean[] aResults = new boolean[10]; + aResults[0] = inject_updateEntity(); + aResults[1] = inject_canSmelt(); + aResults[2] = inject_smeltItem(); + aResults[3] = inject_getFumeFunnels(); + aResults[4] = inject_isFumeFunnel(); + aResults[5] = inject_getFumeFunnelsChance(); + aResults[6] = inject_getFumeFunnelChance(); + aResults[7] = inject_getCookTime(); + aResults[8] = inject_generateByProduct(); + aResults[9] = inject_createByProduct(); + for (boolean b : aResults) { + if (!b) { + log("Patching failed."); + return false; + } + } + log("Patching Success."); + return true; + } + + private boolean inject_updateEntity() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PUBLIC, "updateEntity", "()V", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(151, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "updateEntity", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)V", + false); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLineNumber(152, l1); + mv.visitInsn(RETURN); + Label l2 = new Label(); + mv.visitLabel(l2); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + return true; + } + + private boolean inject_canSmelt() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "canSmelt", "()Z", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(155, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "canSmelt", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)Z", + false); + mv.visitInsn(IRETURN); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + return true; + } + + private boolean inject_smeltItem() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PUBLIC, "smeltItem", "()V", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(159, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "smeltItem", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)V", + false); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLineNumber(160, l1); + mv.visitInsn(RETURN); + Label l2 = new Label(); + mv.visitLabel(l2); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + return true; + } + + private boolean inject_getFumeFunnels() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "getFumeFunnels", "()I", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(163, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "getFumeFunnels", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)I", + false); + mv.visitInsn(IRETURN); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + return true; + } + + private boolean inject_isFumeFunnel() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "isFumeFunnel", "(IIII)Z", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(167, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ILOAD, 1); + mv.visitVarInsn(ILOAD, 2); + mv.visitVarInsn(ILOAD, 3); + mv.visitVarInsn(ILOAD, 4); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "isFumeFunnel", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;IIII)Z", + false); + mv.visitInsn(IRETURN); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); + mv.visitLocalVariable("xCoord", "I", null, l0, l1, 1); + mv.visitLocalVariable("yCoord", "I", null, l0, l1, 2); + mv.visitLocalVariable("zCoord", "I", null, l0, l1, 3); + mv.visitLocalVariable("meta", "I", null, l0, l1, 4); + mv.visitMaxs(5, 5); + mv.visitEnd(); + + return true; + } + + private boolean inject_getFumeFunnelsChance() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "getFumeFunnelsChance", "()D", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(171, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "getFumeFunnelsChance", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)D", + false); + mv.visitInsn(DRETURN); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); + mv.visitMaxs(2, 1); + mv.visitEnd(); + + return true; + } + + private boolean inject_getFumeFunnelChance() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "getFumeFunnelChance", "(IIII)D", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(175, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ALOAD, 0); + mv.visitFieldInsn( + GETFIELD, "com/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven", "xCoord", "I"); + mv.visitVarInsn(ALOAD, 0); + mv.visitFieldInsn( + GETFIELD, "com/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven", "yCoord", "I"); + mv.visitVarInsn(ALOAD, 0); + mv.visitFieldInsn( + GETFIELD, "com/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven", "zCoord", "I"); + mv.visitVarInsn(ILOAD, 4); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "getFumeFunnelChance", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;IIII)D", + false); + mv.visitInsn(DRETURN); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); + mv.visitLocalVariable("x", "I", null, l0, l1, 1); + mv.visitLocalVariable("y", "I", null, l0, l1, 2); + mv.visitLocalVariable("z", "I", null, l0, l1, 3); + mv.visitLocalVariable("meta", "I", null, l0, l1, 4); + mv.visitMaxs(5, 5); + mv.visitEnd(); + + return true; + } + + private boolean inject_getCookTime() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "getCookTime", "()I", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(178, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "getCookTime", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;)I", + false); + mv.visitInsn(IRETURN); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l1, 0); + mv.visitMaxs(1, 1); + mv.visitEnd(); + + return true; + } + + private boolean inject_generateByProduct() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "generateByProduct", "(L" + mItemStack + ";)V", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(182, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ALOAD, 1); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "generateByProduct", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;L" + mItemStack + ";)V", + false); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLineNumber(183, l1); + mv.visitInsn(RETURN); + Label l2 = new Label(); + mv.visitLabel(l2); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); + mv.visitLocalVariable("itemstack", "L" + mItemStack + ";", null, l0, l2, 1); + mv.visitMaxs(2, 2); + mv.visitEnd(); + + return true; + } + + private boolean inject_createByProduct() { + MethodVisitor mv; + + mv = getWriter().visitMethod(ACC_PRIVATE, "createByProduct", "(L" + mItemStack + ";)V", null, null); + mv.visitCode(); + Label l0 = new Label(); + mv.visitLabel(l0); + mv.visitLineNumber(186, l0); + mv.visitVarInsn(ALOAD, 0); + mv.visitVarInsn(ALOAD, 1); + mv.visitMethodInsn( + INVOKESTATIC, + "alkalus/main/core/util/WitchesOvenUtils", + "createByProduct", + "(Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;L" + mItemStack + ";)V", + false); + Label l1 = new Label(); + mv.visitLabel(l1); + mv.visitLineNumber(187, l1); + mv.visitInsn(RETURN); + Label l2 = new Label(); + mv.visitLabel(l2); + mv.visitLocalVariable( + "this", "Lcom/emoniph/witchery/blocks/BlockWitchesOven$TileEntityWitchesOven;", null, l0, l2, 0); + mv.visitLocalVariable("byProduct", "L" + mItemStack + ";", null, l0, l2, 1); + mv.visitMaxs(2, 2); + mv.visitEnd(); + + return true; + } + + @Override + public String[] getMethodNamesToStrip() { + return new String[] { + "getCookTime", + "updateEntity", + "canSmelt", + "smeltItem", + "getFumeFunnels", + "isFumeFunnel", + "getFumeFunnelsChance", + "getFumeFunnelChance", + "getCookTime", + "generateByProduct", + "createByProduct", + }; + } + + @Override + public String[] getMethodDescriptorsToStrip() { + return null; + } + + @Override + public String getTransformerName() { + return "Witches Oven Fix"; + } + + @Override + protected boolean runInjectorMultipleTimes() { + return false; + } } diff --git a/src/main/java/alkalus/main/core/WitcheryExtras.java b/src/main/java/alkalus/main/core/WitcheryExtras.java index dd484f0..63b3c4c 100644 --- a/src/main/java/alkalus/main/core/WitcheryExtras.java +++ b/src/main/java/alkalus/main/core/WitcheryExtras.java @@ -1,9 +1,5 @@ package alkalus.main.core; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - import alkalus.main.api.plugin.base.BasePluginWitchery; import alkalus.main.core.command.DebugCommand; import alkalus.main.core.entities.PredictionHandler; @@ -11,118 +7,122 @@ import alkalus.main.core.util.Logger; import alkalus.main.core.util.Utils; import cpw.mods.fml.common.Mod; -import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.Mod.EventHandler; +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.event.FMLServerStartingEvent; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; -@Mod(modid = WitcheryExtras.MODID, name = WitcheryExtras.NAME, version = WitcheryExtras.VERSION, dependencies = "required-after:Forge; after:witchery;") +@Mod( + modid = WitcheryExtras.MODID, + name = WitcheryExtras.NAME, + version = WitcheryExtras.VERSION, + dependencies = "required-after:Forge; after:witchery;") public class WitcheryExtras { - - - public static final String MODID = "WitcheryExtras"; - public static final String NAME = "Witchery++"; - public static final String VERSION = "GRADLETOKEN_VERSION"; - private static final Logger log4j = new Logger(); - - private static final Map mPreInitEvents; - private static final Map mInitEvents; - private static final Map mPostInitEvents; - - - //Static Initialization block - static { - mPreInitEvents = new HashMap(); - mInitEvents = new HashMap(); - mPostInitEvents = new HashMap(); - } - - @Mod.Instance(MODID) - public static WitcheryExtras instance; - @SidedProxy(clientSide = "alkalus.main.core.proxy.Proxy_Client", serverSide = "alkalus.main.core.proxy.Proxy_Server") - public static Proxy_Common proxy; - - - - - @Mod.EventHandler - public synchronized void preInit(final FMLPreInitializationEvent e) { - log(0, "Loading "+NAME+" - v"+VERSION); - proxy.preInit(e); - for (BasePluginWitchery bwp : getMpreinitevents()) { - log(0, "Loading Plugin: "+bwp.getPluginName()+" | Phase: Pre-Init"); - bwp.preInit(); - } - } - - @Mod.EventHandler - public synchronized void init(final FMLInitializationEvent e) { - proxy.init(e); - for (BasePluginWitchery bwp : getMinitevents()) { - log(0, "Loading Plugin: "+bwp.getPluginName()+" | Phase: Init"); - bwp.init(); - } - proxy.registerRenderers(); - } - - @Mod.EventHandler - public synchronized void postInit(final FMLPostInitializationEvent e) { - proxy.postInit(e); - for (BasePluginWitchery bwp : getMpostinitevents()) { - log(0, "Loading Plugin: "+bwp.getPluginName()+" | Phase: Post-Init"); - bwp.postInit(); - } - PredictionHandler.adjustPredictions(); - } - - @EventHandler - public synchronized void serverStarting(final FMLServerStartingEvent event) { - if (Utils.isDevEnv()) { - event.registerServerCommand(new DebugCommand()); - } - } - - public static final void log(int level, String text) { - if (level<=0) { - log4j.INFO(text); - } - else if (level==1) { - log4j.WARNING(text); - } - else { - log4j.ERROR(text); - } - } - - - //Custom Content Loader - public static synchronized final Collection getMpreinitevents() { - return mPreInitEvents.values(); - } - - public static synchronized final Collection getMinitevents() { - return mInitEvents.values(); - } - - public static synchronized final Collection getMpostinitevents() { - return mPostInitEvents.values(); - } - - private static int mID_1 = 0; - public static synchronized final void addEventPreInit(BasePluginWitchery basePluginWitchery) { - mPreInitEvents.put(mID_1++, basePluginWitchery); - } - - private static int mID_2 = 0; - public static synchronized final void addEventInit(BasePluginWitchery minitevents) { - mInitEvents.put(mID_2++, minitevents); - } - - private static int mID_3 = 0; - public static synchronized final void addEventPostInit(BasePluginWitchery mpostinitevents) { - mPostInitEvents.put(mID_3++, mpostinitevents); - } - + + public static final String MODID = "WitcheryExtras"; + public static final String NAME = "Witchery++"; + public static final String VERSION = "GRADLETOKEN_VERSION"; + private static final Logger log4j = new Logger(); + + private static final Map mPreInitEvents; + private static final Map mInitEvents; + private static final Map mPostInitEvents; + + // Static Initialization block + static { + mPreInitEvents = new HashMap(); + mInitEvents = new HashMap(); + mPostInitEvents = new HashMap(); + } + + @Mod.Instance(MODID) + public static WitcheryExtras instance; + + @SidedProxy( + clientSide = "alkalus.main.core.proxy.Proxy_Client", + serverSide = "alkalus.main.core.proxy.Proxy_Server") + public static Proxy_Common proxy; + + @Mod.EventHandler + public synchronized void preInit(final FMLPreInitializationEvent e) { + log(0, "Loading " + NAME + " - v" + VERSION); + proxy.preInit(e); + for (BasePluginWitchery bwp : getMpreinitevents()) { + log(0, "Loading Plugin: " + bwp.getPluginName() + " | Phase: Pre-Init"); + bwp.preInit(); + } + } + + @Mod.EventHandler + public synchronized void init(final FMLInitializationEvent e) { + proxy.init(e); + for (BasePluginWitchery bwp : getMinitevents()) { + log(0, "Loading Plugin: " + bwp.getPluginName() + " | Phase: Init"); + bwp.init(); + } + proxy.registerRenderers(); + } + + @Mod.EventHandler + public synchronized void postInit(final FMLPostInitializationEvent e) { + proxy.postInit(e); + for (BasePluginWitchery bwp : getMpostinitevents()) { + log(0, "Loading Plugin: " + bwp.getPluginName() + " | Phase: Post-Init"); + bwp.postInit(); + } + PredictionHandler.adjustPredictions(); + } + + @EventHandler + public synchronized void serverStarting(final FMLServerStartingEvent event) { + if (Utils.isDevEnv()) { + event.registerServerCommand(new DebugCommand()); + } + } + + public static final void log(int level, String text) { + if (level <= 0) { + log4j.INFO(text); + } else if (level == 1) { + log4j.WARNING(text); + } else { + log4j.ERROR(text); + } + } + + // Custom Content Loader + public static final synchronized Collection getMpreinitevents() { + return mPreInitEvents.values(); + } + + public static final synchronized Collection getMinitevents() { + return mInitEvents.values(); + } + + public static final synchronized Collection getMpostinitevents() { + return mPostInitEvents.values(); + } + + private static int mID_1 = 0; + + public static final synchronized void addEventPreInit(BasePluginWitchery basePluginWitchery) { + mPreInitEvents.put(mID_1++, basePluginWitchery); + } + + private static int mID_2 = 0; + + public static final synchronized void addEventInit(BasePluginWitchery minitevents) { + mInitEvents.put(mID_2++, minitevents); + } + + private static int mID_3 = 0; + + public static final synchronized void addEventPostInit(BasePluginWitchery mpostinitevents) { + mPostInitEvents.put(mID_3++, mpostinitevents); + } } diff --git a/src/main/java/alkalus/main/core/command/DebugCommand.java b/src/main/java/alkalus/main/core/command/DebugCommand.java index ff50ce1..d946a4f 100644 --- a/src/main/java/alkalus/main/core/command/DebugCommand.java +++ b/src/main/java/alkalus/main/core/command/DebugCommand.java @@ -1,18 +1,16 @@ package alkalus.main.core.command; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.emoniph.witchery.infusion.Infusion; -import com.mojang.authlib.GameProfile; - import alkalus.main.core.WitcheryExtras; import alkalus.main.core.util.ReflectionUtils; +import com.emoniph.witchery.infusion.Infusion; +import com.mojang.authlib.GameProfile; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import net.minecraft.client.Minecraft; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; @@ -24,147 +22,144 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; - public class DebugCommand implements ICommand { - private final List aliases; - - public DebugCommand(){ - this.aliases = new ArrayList<>(); - this.aliases.add("WD"); - this.aliases.add("wd"); - } - - @Override - public int compareTo(final Object o){ - if (o instanceof Comparable) { - @SuppressWarnings("unchecked") - Comparable a = (Comparable) o; - if (a.equals(this)) { - return 0; - } - else { - return -1; - } - } - return -1; - } - - @Override - public String getCommandName(){ - return "witcherydebug"; - - } - - - // Use '/gtpp' along with 'logging' or 'debug' to toggle Debug mode and Logging. - // Using nothing after the command toggles both to their opposite states respectively. - @Override - public String getCommandUsage(final ICommandSender var1){ - return "/witcherydebug"; - } - - @Override - public List getCommandAliases(){ - return this.aliases; - } - - @Override - public void processCommand(final ICommandSender S, final String[] argString){ - EntityPlayer aPlayer = getPlayer(S.getCommandSenderName()); - if (aPlayer != null) { - if (argString != null) { - if (argString[0] != null && argString[0].length() > 0) { - if (argString[0].equalsIgnoreCase("name")) { - GameProfile aProfile = aPlayer.getGameProfile(); - if (!aPlayer.getCommandSenderName().equalsIgnoreCase("emoniph")) { - if (aProfile != null) { - Field aNameField = ReflectionUtils.getField(GameProfile.class, "name"); - ReflectionUtils.setField(aProfile, aNameField, "emoniph"); - } - } - if (!aPlayer.getDisplayName().equalsIgnoreCase("emoniph")) { - Field aNameField2 = ReflectionUtils.getField(EntityPlayer.class, "displayname"); - ReflectionUtils.setField(aPlayer, aNameField2, "emoniph"); - } - if (!aProfile.getName().equalsIgnoreCase("emoniph")) { - aProfile = new GameProfile(aPlayer.getUniqueID(), "emoniph"); - Field aProfileField = ReflectionUtils.getField(EntityPlayer.class, "field_146106_i"); - ReflectionUtils.setField(aPlayer, aProfileField, aProfile); - } - } - if (argString[0].equalsIgnoreCase("predictions") || argString[0].equalsIgnoreCase("pred")) { - NBTTagCompound nbtPlayer = Infusion.getNBT(aPlayer); - if(nbtPlayer != null && nbtPlayer.hasKey("WITCPredict")) { - NBTTagCompound nbtRoot = nbtPlayer.getCompoundTag("WITCPredict"); - NBTTagList nbtList = nbtRoot.getTagList("WITCPreList", 10); - int aCount = 0; - while(nbtList.tagCount() > 0) { - nbtList.removeTag(0); - aCount++; - } - String aChatMessage = "Removed "+aCount+" Prediction Tags."; - if (aPlayer instanceof EntityPlayerMP && aChatMessage != null) { - aPlayer.addChatComponentMessage(new ChatComponentText(aChatMessage)); - } - WitcheryExtras.log(1, "Removed "+aCount+" Prediction Tags."); - } - } - } - } - } - else { - WitcheryExtras.log(2, "Player was null."); - } - } - - @Override - public boolean canCommandSenderUseCommand(final ICommandSender var1){ - return true; - } - - @Override - public List addTabCompletionOptions(final ICommandSender var1, final String[] var2){ - ArrayList aTabCompletes = new ArrayList(); - return aTabCompletes; - } - - @Override - public boolean isUsernameIndex(final String[] var1, final int var2){ - return false; - } - - public boolean playerUsesCommand(final World W, final EntityPlayer P, final int cost){ - return true; - } - - @SideOnly(Side.CLIENT) - private EntityPlayer getClientPlayer() { - return Minecraft.getMinecraft().thePlayer; - } - - private EntityPlayer getPlayer(final String name){ - try{ - - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { - WitcheryExtras.log(2, "Using Clientside Player Object."); - return getClientPlayer(); - } - final List i = new ArrayList<>(); - final Iterator iterator = MinecraftServer.getServer().getConfigurationManager().playerEntityList.iterator(); - while (iterator.hasNext()) { - i.add((iterator.next())); - } - WitcheryExtras.log(2, "Looking for Player named: "+name); - for (final EntityPlayer temp : i) { - WitcheryExtras.log(2, "Found Player with name: "+temp.getCommandSenderName()); - if (temp.getCommandSenderName().equalsIgnoreCase(name)){ - return temp; - } - } - } - catch(final Throwable e){} - return null; - } - -} \ No newline at end of file + private final List aliases; + + public DebugCommand() { + this.aliases = new ArrayList<>(); + this.aliases.add("WD"); + this.aliases.add("wd"); + } + + @Override + public int compareTo(final Object o) { + if (o instanceof Comparable) { + @SuppressWarnings("unchecked") + Comparable a = (Comparable) o; + if (a.equals(this)) { + return 0; + } else { + return -1; + } + } + return -1; + } + + @Override + public String getCommandName() { + return "witcherydebug"; + } + + // Use '/gtpp' along with 'logging' or 'debug' to toggle Debug mode and Logging. + // Using nothing after the command toggles both to their opposite states respectively. + @Override + public String getCommandUsage(final ICommandSender var1) { + return "/witcherydebug"; + } + + @Override + public List getCommandAliases() { + return this.aliases; + } + + @Override + public void processCommand(final ICommandSender S, final String[] argString) { + EntityPlayer aPlayer = getPlayer(S.getCommandSenderName()); + if (aPlayer != null) { + if (argString != null) { + if (argString[0] != null && argString[0].length() > 0) { + if (argString[0].equalsIgnoreCase("name")) { + GameProfile aProfile = aPlayer.getGameProfile(); + if (!aPlayer.getCommandSenderName().equalsIgnoreCase("emoniph")) { + if (aProfile != null) { + Field aNameField = ReflectionUtils.getField(GameProfile.class, "name"); + ReflectionUtils.setField(aProfile, aNameField, "emoniph"); + } + } + if (!aPlayer.getDisplayName().equalsIgnoreCase("emoniph")) { + Field aNameField2 = ReflectionUtils.getField(EntityPlayer.class, "displayname"); + ReflectionUtils.setField(aPlayer, aNameField2, "emoniph"); + } + if (!aProfile.getName().equalsIgnoreCase("emoniph")) { + aProfile = new GameProfile(aPlayer.getUniqueID(), "emoniph"); + Field aProfileField = ReflectionUtils.getField(EntityPlayer.class, "field_146106_i"); + ReflectionUtils.setField(aPlayer, aProfileField, aProfile); + } + } + if (argString[0].equalsIgnoreCase("predictions") || argString[0].equalsIgnoreCase("pred")) { + NBTTagCompound nbtPlayer = Infusion.getNBT(aPlayer); + if (nbtPlayer != null && nbtPlayer.hasKey("WITCPredict")) { + NBTTagCompound nbtRoot = nbtPlayer.getCompoundTag("WITCPredict"); + NBTTagList nbtList = nbtRoot.getTagList("WITCPreList", 10); + int aCount = 0; + while (nbtList.tagCount() > 0) { + nbtList.removeTag(0); + aCount++; + } + String aChatMessage = "Removed " + aCount + " Prediction Tags."; + if (aPlayer instanceof EntityPlayerMP && aChatMessage != null) { + aPlayer.addChatComponentMessage(new ChatComponentText(aChatMessage)); + } + WitcheryExtras.log(1, "Removed " + aCount + " Prediction Tags."); + } + } + } + } + } else { + WitcheryExtras.log(2, "Player was null."); + } + } + + @Override + public boolean canCommandSenderUseCommand(final ICommandSender var1) { + return true; + } + + @Override + public List addTabCompletionOptions(final ICommandSender var1, final String[] var2) { + ArrayList aTabCompletes = new ArrayList(); + return aTabCompletes; + } + + @Override + public boolean isUsernameIndex(final String[] var1, final int var2) { + return false; + } + + public boolean playerUsesCommand(final World W, final EntityPlayer P, final int cost) { + return true; + } + + @SideOnly(Side.CLIENT) + private EntityPlayer getClientPlayer() { + return Minecraft.getMinecraft().thePlayer; + } + + private EntityPlayer getPlayer(final String name) { + try { + + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) { + WitcheryExtras.log(2, "Using Clientside Player Object."); + return getClientPlayer(); + } + final List i = new ArrayList<>(); + final Iterator iterator = MinecraftServer.getServer() + .getConfigurationManager() + .playerEntityList + .iterator(); + while (iterator.hasNext()) { + i.add((iterator.next())); + } + WitcheryExtras.log(2, "Looking for Player named: " + name); + for (final EntityPlayer temp : i) { + WitcheryExtras.log(2, "Found Player with name: " + temp.getCommandSenderName()); + if (temp.getCommandSenderName().equalsIgnoreCase(name)) { + return temp; + } + } + } catch (final Throwable e) { + } + return null; + } +} diff --git a/src/main/java/alkalus/main/core/crafting/OvenRecipes.java b/src/main/java/alkalus/main/core/crafting/OvenRecipes.java index 7125b9c..15949ec 100644 --- a/src/main/java/alkalus/main/core/crafting/OvenRecipes.java +++ b/src/main/java/alkalus/main/core/crafting/OvenRecipes.java @@ -1,393 +1,478 @@ package alkalus.main.core.crafting; -import java.util.ArrayList; - -import com.emoniph.witchery.Witchery; - import alkalus.main.core.WitcheryExtras; import alkalus.main.core.util.AutoMap; import alkalus.main.core.util.Pair; import alkalus.main.core.util.Utils; +import com.emoniph.witchery.Witchery; +import java.util.ArrayList; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; public class OvenRecipes { - - private static final ArrayList mRecipeMap = new ArrayList(); - - public static final ArrayList getRecipeMap() { - return mRecipeMap; - } - - public static void generateDefaultOvenRecipes() { - - //Remove recipe for the old Witches Oven - //Utils.removeAllCraftingRecipesByOutputItem(Utils.simpleMetaStack(Witchery.Blocks.OVEN_IDLE, 0, 1)); - //GameRegistry.addShapedRecipe(Utils.simpleMetaStack(WitcheryExtras.OVEN_IDLE, 0, 1), new Object[] { " s ", "ibi", "isi", Character.valueOf('s'), new ItemStack(Blocks.iron_bars), Character.valueOf('b'), new ItemStack(Blocks.furnace), Character.valueOf('i'), new ItemStack(Items.iron_ingot) }); - - //Vanilla Saplings - addRecipe(Utils.simpleMetaStack(Blocks.sapling, 0, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemExhaleOfTheHornedOne.createStack(1)); //Oak - 0 - addRecipe(Utils.simpleMetaStack(Blocks.sapling, 1, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); //Spruce - 1 - addRecipe(Utils.simpleMetaStack(Blocks.sapling, 2, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); //Birch - 2 - addRecipe(Utils.simpleMetaStack(Blocks.sapling, 3, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemFoulFume.createStack(1)); //Jungle - 3 - addRecipe(Utils.simpleMetaStack(Blocks.sapling, 4, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); //Acacia - 4 - addRecipe(Utils.simpleMetaStack(Blocks.sapling, 5, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); //Dark Oak - 5 - - //Witchery Saplings - addRecipe(Utils.simpleMetaStack(Witchery.Blocks.SAPLING, 0, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemWhiffOfMagic.createStack(1)); - addRecipe(Utils.simpleMetaStack(Witchery.Blocks.SAPLING, 1, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemReekOfMisfortune.createStack(1)); - addRecipe(Utils.simpleMetaStack(Witchery.Blocks.SAPLING, 2, 1), 1, Witchery.Items.GENERIC.itemAshWood.createStack(1), Witchery.Items.GENERIC.itemOdourOfPurity.createStack(1)); - - //Raw Materials - addRecipe("logWood", 1, Witchery.Items.GENERIC.itemFoulFume.createStack(1)); - addRecipe("meatRaw", 1, Witchery.Items.GENERIC.itemFoulFume.createStack(1)); - - //Test - //addRecipe(Utils.simpleMetaStack(Blocks.diamond_ore, 0, 1), 1, Witchery.Items.GENERIC.itemCreeperHeart.createStack(1), Witchery.Items.GENERIC.itemRedstoneSoup.createStack(1)); //Dark Oak - 5 - } - - private final static ItemStack createStack(final int stackSize) { - return new ItemStack((Item) Witchery.Items.GENERIC, stackSize, 27); - } - - public static ItemStack getEmptyJar(int amount) { - return createStack(amount); - } - - public static ItemStack getWitcheryItemByID(int id, int stackSize) { - return new ItemStack((Item) Witchery.Items.GENERIC, stackSize, id); - } - - private OvenRecipes() { - - } - - /** @param input1 - The Input Item. - * @param jars - The required amount of Jars. - * @param jarOutput - The type of Jar output. - * @param outputAmount - Amount of outputs, output item is based on furnace recipe of input item. - * @return - A new {@link OverRecipe} object. - */ - public static OvenRecipe addRecipe(final ItemStack input1, final int jars, final ItemStack jarOutput) { - return addRecipe(input1, "", jars, null, 0, jarOutput, jars); - } - - /** @param input1 - The Input Item. - * @param jars - The required amount of Jars. - * @param customOutput - A Custom output, output size reflect Itemstack size passed in. - * @param jarOutput - The type of Jar output. - * @param outputAmount - Amount of outputs, output item is based on furnace recipe of input item. - * @return - A new {@link OverRecipe} object. - */ - public static OvenRecipe addRecipe(final ItemStack input1, final int jars, final ItemStack customOutput, final ItemStack jarOutput) { - return addRecipe(input1, "", jars, customOutput, customOutput.stackSize, jarOutput, jars); - } - - /** @param input1 - A Valid Oredict String. - * @param jars - The required amount of Jars. - * @param jarOutput - The type of Jar output. - * @param outputAmount - Amount of outputs, output item is based on furnace recipe of input item. - * @return - A new {@link OverRecipe} object. - */ - public static OvenRecipe addRecipe(final String input1, final int jars, final ItemStack jarOutput) { - return addRecipe(null, input1, jars, null, 0, jarOutput, jars); - } - - - /** - * - * @param input1 - The Input Item. - * @param jars - The required amount of Jars. - * @param output0 - A custom ItemStack output. - * @param amt0 - The amount of custom outputs. - * @param output1 - The type of Jar output. - * @param amt1 - The amount of Jars output - * @return - A new {@link OverRecipe} object. - */ - public static OvenRecipe addRecipe(final ItemStack input1, final int jars, final ItemStack output0, int amt0, final ItemStack output1, final int amt1) { - return addRecipe(input1, "", jars, output0, amt0, output1, amt1); - } - - /** - * - * @param input1 - The Input Item. - * @param inputString1 - A Valid Oredict String. - * @param jars - The required amount of Jars. - * @param customOutput - A custom ItemStack output. - * @param amt1 - The amount of custom outputs. - * @param outputJarStack - The type of Jar output. - * @param amt2 - The amount of Jars output - * @return - A new {@link OverRecipe} object. - */ - public static OvenRecipe addRecipe( - final ItemStack input1, final String inputString1, final int jars, - final ItemStack customOutput, final int amt1, final ItemStack outputJarStack, final int amt2) { - - //Build Inputs - ItemStack mInputStack = null; - String mInputString = null; - int mJars = 0; - if (input1 != null) { - mInputStack = input1; - } - else if (inputString1 != null && !inputString1.equals("")) { - mInputString = inputString1; - } - else { - WitcheryExtras.log(0, "Failed adding a Oven recipe for: INVALID."); - return null; - } - - WitcheryExtras.log(0, "Trying to add an Oven Recipe for "+(mInputStack != null ? mInputStack.getDisplayName() : mInputString)); - - mJars = jars; - //Build Outputs - ItemStack mOutputStack = null; - int mOutputAmount = 0; - ItemStack mJarOutputStack = null; - int mJarOutputAmount = 0; - boolean y[] = new boolean[2]; - - //Furnace Output - if (customOutput != null && amt1 > 0) { - mOutputStack = customOutput; - mOutputAmount = amt1; - y[0] = true; - } - else { - ItemStack[] w = Utils.getAllItemsFromOreDictEntry(inputString1); - ItemStack s = null; - if (w != null && w.length > 0) { - for (int i=0;i 64 || gh.stackSize <= 0) { - gh.stackSize = 1; - } - s = Utils.getSimpleStack(gh.copy(), gh.stackSize); - break; - } - } - } - else { - WitcheryExtras.log(0, "Found no entries in OreDict for "+inputString1); - } - if (s != null) { - mOutputStack = s; - mOutputAmount = s.stackSize; - y[0] = true; - } - else { - WitcheryExtras.log(0, "Set Y0 to False"); - y[0] = false; - } - } - //Jar Output - if (outputJarStack != null && (amt2 > 0 && amt2 == jars)) { - mJarOutputStack = outputJarStack; - mJarOutputAmount = amt2; - y[1] = true; - } - else { - y[1] = false; - WitcheryExtras.log(0, "Set Y1 to False"); - } - if (y[0] && y[1]) { - OvenRecipe recipe; - if (mInputStack != null) { - recipe = new OvenRecipe(mInputStack.copy(), mJars, mOutputStack.copy(), mOutputAmount, mJarOutputStack.copy(), mJarOutputAmount); - } - else { - recipe = new OvenRecipe(mInputString, mJars, mOutputStack.copy(), mOutputAmount, mJarOutputStack.copy(), mJarOutputAmount); - } - mRecipeMap.add(recipe); - WitcheryExtras.log(0, "Added an Oven Recipe" + recipe.getDescription()); - return recipe; - } - else { - WitcheryExtras.log(0, "Failed when trying to add an Oven Recipe for "+(mInputStack != null ? mInputStack.getDisplayName() : mInputString)); - return null; - } - } - - - - - - /** - * Returns an {@link OverRecipe} based on input item and an amount of jars. - * @param input1 - An ItemStack - * @param jars - Amount of Jars - * @return - The Closest Matching {@link OverRecipe}. - */ - public static OvenRecipe getOvenResult(final ItemStack input1, final int jars) { - for (final OvenRecipe recipe : mRecipeMap) { - if (recipe.isInputMatch(input1, jars)) { - return recipe; - } - } - return null; - } - - /** - * Returns a {@link OverRecipe} based on an output item. - * @param result - The output item. - * @return - The first Matching {@link OverRecipe}. - */ - public static OvenRecipe findRecipeFor(final ItemStack result) { - for (final OvenRecipe recipe : mRecipeMap) { - if (recipe.resultsIn(result)) { - return recipe; - } - } - return null; - } - /** - * Returns a {@link OverRecipe} based on an input item. This may not always return the same recipe. - * @param input1 - An ItemStack - * @return - The first Matching {@link OverRecipe}. - */ - public static OvenRecipe findRecipeUsing(final ItemStack ingredient) { - for (final OvenRecipe recipe : mRecipeMap) { - if (recipe.uses(ingredient)) { - return recipe; - } - } - return null; - } - - public static class OvenRecipe { - public final String validOreDictInput; - public final ItemStack inputs; - public final int jars; - public final ItemStack output; - public final ItemStack outputJar; - public final int outputAmount1; - public final int outputAmountJar; - public final AutoMap> outputs = new AutoMap>(); - - - /** - * - * @param input1 - The {@link ItemStack} to be burned in the oven. - * @param jars - An {@link int} for the amount of Jars required. - * @param output1 - The {@link ItemStack} which is a result of using the Oven. - * @param amount1 - An {@link int} for the amount of {@link output1} given. - * @param output2 - The {@link ItemStack} which is a filled Jar. - * @param amount2 - An {@link int} for the amount of {@link output2} given. - */ - private OvenRecipe(final String oreDictSub, final int jars, final ItemStack output1, final int amount1, final ItemStack output2, final int amount2) { - this(null, oreDictSub, jars, output1, amount1, output2, amount2); - } - - /** - * - * @param input1 - The {@link ItemStack} to be burned in the oven. - * @param jars - An {@link int} for the amount of Jars required. - * @param output1 - The {@link ItemStack} which is a result of using the Oven. - * @param amount1 - An {@link int} for the amount of {@link output1} given. - * @param output2 - The {@link ItemStack} which is a filled Jar. - * @param amount2 - An {@link int} for the amount of {@link output2} given. - */ - private OvenRecipe(final ItemStack input1, final int jars, final ItemStack output1, final int amount1, final ItemStack output2, final int amount2) { - this(input1, "", jars, output1, amount1, output2, amount2); - } - - /** - * - * @param input1 - The {@link ItemStack} to be burned in the oven. - * @param jars - An {@link int} for the amount of Jars required. - * @param output1 - The {@link ItemStack} which is a result of using the Oven. - * @param amount1 - An {@link int} for the amount of {@link output1} given. - * @param output2 - The {@link ItemStack} which is a filled Jar. - * @param amount2 - An {@link int} for the amount of {@link output2} given. - */ - private OvenRecipe(final ItemStack input1, String oreDict, final int jars, final ItemStack output1, final int amount1, final ItemStack output2, final int amount2) { - this.inputs = input1; - this.validOreDictInput = oreDict; - this.jars = jars; - this.output = output1; - this.outputJar = output2; - this.outputAmount1 = amount1; - this.outputAmountJar = amount2; - Pair a1 = new Pair(output1, amount1); - Pair a2 = new Pair(output1, amount1); - this.outputs.put(a1); - this.outputs.put(a2); - } - - private boolean isInputMatch(final ItemStack intput1, int amt1) { - return (this.jars == 0 || ((isMatch(intput1, this.inputs) && amt1 >= this.jars)) || (!this.validOreDictInput.equals("") && Utils.hasValidOreDictTag(this.validOreDictInput, intput1))); - } - - @SuppressWarnings("unused") - private boolean isMatch(final ItemStack output1, int amt1, final ItemStack output2, int amt2) { - return (this.jars == 0 || ((amt1 == this.outputAmount1 && amt2 == this.outputAmountJar) && (OvenRecipe.isMatch(output1, this.output) && OvenRecipe.isMatch(output2, outputJar)))); - } - - public static boolean isMatch(final ItemStack a, final ItemStack b) { - return (a == null && b == null) || (a != null && b != null && a.getItem() == b.getItem() - && (!a.getHasSubtypes() || a.getItemDamage() == b.getItemDamage())); - } - - public static boolean isMatch(final ItemStack a, final ItemStack b, String oreName) { - return ((Utils.hasValidOreDictTag(oreName, a) && Utils.hasValidOreDictTag(oreName, b)) || a == null && b == null) || (a != null && b != null && a.getItem() == b.getItem() - && (!a.getHasSubtypes() || a.getItemDamage() == b.getItemDamage())); - } - - public int getJars() { - return this.jars; - } - - public ItemStack[] getOutputs() { - ItemStack x[] = new ItemStack[2]; - Pair a1 = outputs.get(0); - Pair a2 = outputs.get(1); - x[0] = Utils.getSimpleStack(a1.getKey(), a1.getValue()); - x[1] = Utils.getSimpleStack(a2.getKey(), a2.getValue()); - return x; - } - - public String getDescription() { - String[] y = new String[]{"descriptor", - ("Input: " + (inputs != null ? this.inputs.getDisplayName() : "No Item") + " x" +(inputs != null ? inputs.stackSize : 0)), - ("Jars Required: " + this.jars), - ("Output: " + (output != null ? this.output.getDisplayName() : "No Item") + " x" +(output != null ? output.stackSize : 0)), - ("Jar Output: " + this.outputJar.getDisplayName() + " x"+jars), - ("OreDict: " + this.validOreDictInput) - }; - String z = ""; - for (String x : y) { - WitcheryExtras.log(0, x); - } - for (String x : y) { - z += "."+x; - } - return z; - } - - public boolean resultsIn(final ItemStack result) { - for (final ItemStack stack : getOutputs()) { - if (stack != null && stack.isItemEqual(result)) { - return true; - } - } - return false; - } - - public boolean uses(final ItemStack ingredient) { - if (this.inputs != null && this.inputs.isItemEqual(ingredient)) { - return true; - } - return Witchery.Items.GENERIC.itemEmptyClayJar.isMatch(ingredient) && this.jars > 0; - } - - public boolean isValid() { - return inputs != null && output != null; - } - } - -} \ No newline at end of file + + private static final ArrayList mRecipeMap = new ArrayList(); + + public static final ArrayList getRecipeMap() { + return mRecipeMap; + } + + public static void generateDefaultOvenRecipes() { + + // Remove recipe for the old Witches Oven + // Utils.removeAllCraftingRecipesByOutputItem(Utils.simpleMetaStack(Witchery.Blocks.OVEN_IDLE, 0, 1)); + // GameRegistry.addShapedRecipe(Utils.simpleMetaStack(WitcheryExtras.OVEN_IDLE, 0, 1), new Object[] { " s ", + // "ibi", "isi", Character.valueOf('s'), new ItemStack(Blocks.iron_bars), Character.valueOf('b'), new + // ItemStack(Blocks.furnace), Character.valueOf('i'), new ItemStack(Items.iron_ingot) }); + + // Vanilla Saplings + addRecipe( + Utils.simpleMetaStack(Blocks.sapling, 0, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemExhaleOfTheHornedOne.createStack(1)); // Oak - 0 + addRecipe( + Utils.simpleMetaStack(Blocks.sapling, 1, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); // Spruce - 1 + addRecipe( + Utils.simpleMetaStack(Blocks.sapling, 2, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); // Birch - 2 + addRecipe( + Utils.simpleMetaStack(Blocks.sapling, 3, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemFoulFume.createStack(1)); // Jungle - 3 + addRecipe( + Utils.simpleMetaStack(Blocks.sapling, 4, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); // Acacia - 4 + addRecipe( + Utils.simpleMetaStack(Blocks.sapling, 5, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); // Dark Oak - 5 + + // Witchery Saplings + addRecipe( + Utils.simpleMetaStack(Witchery.Blocks.SAPLING, 0, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemWhiffOfMagic.createStack(1)); + addRecipe( + Utils.simpleMetaStack(Witchery.Blocks.SAPLING, 1, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemReekOfMisfortune.createStack(1)); + addRecipe( + Utils.simpleMetaStack(Witchery.Blocks.SAPLING, 2, 1), + 1, + Witchery.Items.GENERIC.itemAshWood.createStack(1), + Witchery.Items.GENERIC.itemOdourOfPurity.createStack(1)); + + // Raw Materials + addRecipe("logWood", 1, Witchery.Items.GENERIC.itemFoulFume.createStack(1)); + addRecipe("meatRaw", 1, Witchery.Items.GENERIC.itemFoulFume.createStack(1)); + + // Test + // addRecipe(Utils.simpleMetaStack(Blocks.diamond_ore, 0, 1), 1, + // Witchery.Items.GENERIC.itemCreeperHeart.createStack(1), + // Witchery.Items.GENERIC.itemRedstoneSoup.createStack(1)); //Dark Oak - 5 + } + + private static final ItemStack createStack(final int stackSize) { + return new ItemStack((Item) Witchery.Items.GENERIC, stackSize, 27); + } + + public static ItemStack getEmptyJar(int amount) { + return createStack(amount); + } + + public static ItemStack getWitcheryItemByID(int id, int stackSize) { + return new ItemStack((Item) Witchery.Items.GENERIC, stackSize, id); + } + + private OvenRecipes() {} + + /** @param input1 - The Input Item. + * @param jars - The required amount of Jars. + * @param jarOutput - The type of Jar output. + * @param outputAmount - Amount of outputs, output item is based on furnace recipe of input item. + * @return - A new {@link OverRecipe} object. + */ + public static OvenRecipe addRecipe(final ItemStack input1, final int jars, final ItemStack jarOutput) { + return addRecipe(input1, "", jars, null, 0, jarOutput, jars); + } + + /** @param input1 - The Input Item. + * @param jars - The required amount of Jars. + * @param customOutput - A Custom output, output size reflect Itemstack size passed in. + * @param jarOutput - The type of Jar output. + * @param outputAmount - Amount of outputs, output item is based on furnace recipe of input item. + * @return - A new {@link OverRecipe} object. + */ + public static OvenRecipe addRecipe( + final ItemStack input1, final int jars, final ItemStack customOutput, final ItemStack jarOutput) { + return addRecipe(input1, "", jars, customOutput, customOutput.stackSize, jarOutput, jars); + } + + /** @param input1 - A Valid Oredict String. + * @param jars - The required amount of Jars. + * @param jarOutput - The type of Jar output. + * @param outputAmount - Amount of outputs, output item is based on furnace recipe of input item. + * @return - A new {@link OverRecipe} object. + */ + public static OvenRecipe addRecipe(final String input1, final int jars, final ItemStack jarOutput) { + return addRecipe(null, input1, jars, null, 0, jarOutput, jars); + } + + /** + * + * @param input1 - The Input Item. + * @param jars - The required amount of Jars. + * @param output0 - A custom ItemStack output. + * @param amt0 - The amount of custom outputs. + * @param output1 - The type of Jar output. + * @param amt1 - The amount of Jars output + * @return - A new {@link OverRecipe} object. + */ + public static OvenRecipe addRecipe( + final ItemStack input1, + final int jars, + final ItemStack output0, + int amt0, + final ItemStack output1, + final int amt1) { + return addRecipe(input1, "", jars, output0, amt0, output1, amt1); + } + + /** + * + * @param input1 - The Input Item. + * @param inputString1 - A Valid Oredict String. + * @param jars - The required amount of Jars. + * @param customOutput - A custom ItemStack output. + * @param amt1 - The amount of custom outputs. + * @param outputJarStack - The type of Jar output. + * @param amt2 - The amount of Jars output + * @return - A new {@link OverRecipe} object. + */ + public static OvenRecipe addRecipe( + final ItemStack input1, + final String inputString1, + final int jars, + final ItemStack customOutput, + final int amt1, + final ItemStack outputJarStack, + final int amt2) { + + // Build Inputs + ItemStack mInputStack = null; + String mInputString = null; + int mJars = 0; + if (input1 != null) { + mInputStack = input1; + } else if (inputString1 != null && !inputString1.equals("")) { + mInputString = inputString1; + } else { + WitcheryExtras.log(0, "Failed adding a Oven recipe for: INVALID."); + return null; + } + + WitcheryExtras.log( + 0, + "Trying to add an Oven Recipe for " + + (mInputStack != null ? mInputStack.getDisplayName() : mInputString)); + + mJars = jars; + // Build Outputs + ItemStack mOutputStack = null; + int mOutputAmount = 0; + ItemStack mJarOutputStack = null; + int mJarOutputAmount = 0; + boolean y[] = new boolean[2]; + + // Furnace Output + if (customOutput != null && amt1 > 0) { + mOutputStack = customOutput; + mOutputAmount = amt1; + y[0] = true; + } else { + ItemStack[] w = Utils.getAllItemsFromOreDictEntry(inputString1); + ItemStack s = null; + if (w != null && w.length > 0) { + for (int i = 0; i < w.length; i++) { + ItemStack gh = FurnaceRecipes.smelting().getSmeltingResult(w[i]); + if (gh != null) { + gh = gh.copy(); + if (gh.stackSize > 64 || gh.stackSize <= 0) { + gh.stackSize = 1; + } + s = Utils.getSimpleStack(gh.copy(), gh.stackSize); + break; + } + } + } else { + WitcheryExtras.log(0, "Found no entries in OreDict for " + inputString1); + } + if (s != null) { + mOutputStack = s; + mOutputAmount = s.stackSize; + y[0] = true; + } else { + WitcheryExtras.log(0, "Set Y0 to False"); + y[0] = false; + } + } + // Jar Output + if (outputJarStack != null && (amt2 > 0 && amt2 == jars)) { + mJarOutputStack = outputJarStack; + mJarOutputAmount = amt2; + y[1] = true; + } else { + y[1] = false; + WitcheryExtras.log(0, "Set Y1 to False"); + } + if (y[0] && y[1]) { + OvenRecipe recipe; + if (mInputStack != null) { + recipe = new OvenRecipe( + mInputStack.copy(), + mJars, + mOutputStack.copy(), + mOutputAmount, + mJarOutputStack.copy(), + mJarOutputAmount); + } else { + recipe = new OvenRecipe( + mInputString, + mJars, + mOutputStack.copy(), + mOutputAmount, + mJarOutputStack.copy(), + mJarOutputAmount); + } + mRecipeMap.add(recipe); + WitcheryExtras.log(0, "Added an Oven Recipe" + recipe.getDescription()); + return recipe; + } else { + WitcheryExtras.log( + 0, + "Failed when trying to add an Oven Recipe for " + + (mInputStack != null ? mInputStack.getDisplayName() : mInputString)); + return null; + } + } + + /** + * Returns an {@link OverRecipe} based on input item and an amount of jars. + * @param input1 - An ItemStack + * @param jars - Amount of Jars + * @return - The Closest Matching {@link OverRecipe}. + */ + public static OvenRecipe getOvenResult(final ItemStack input1, final int jars) { + for (final OvenRecipe recipe : mRecipeMap) { + if (recipe.isInputMatch(input1, jars)) { + return recipe; + } + } + return null; + } + + /** + * Returns a {@link OverRecipe} based on an output item. + * @param result - The output item. + * @return - The first Matching {@link OverRecipe}. + */ + public static OvenRecipe findRecipeFor(final ItemStack result) { + for (final OvenRecipe recipe : mRecipeMap) { + if (recipe.resultsIn(result)) { + return recipe; + } + } + return null; + } + /** + * Returns a {@link OverRecipe} based on an input item. This may not always return the same recipe. + * @param input1 - An ItemStack + * @return - The first Matching {@link OverRecipe}. + */ + public static OvenRecipe findRecipeUsing(final ItemStack ingredient) { + for (final OvenRecipe recipe : mRecipeMap) { + if (recipe.uses(ingredient)) { + return recipe; + } + } + return null; + } + + public static class OvenRecipe { + public final String validOreDictInput; + public final ItemStack inputs; + public final int jars; + public final ItemStack output; + public final ItemStack outputJar; + public final int outputAmount1; + public final int outputAmountJar; + public final AutoMap> outputs = new AutoMap>(); + + /** + * + * @param input1 - The {@link ItemStack} to be burned in the oven. + * @param jars - An {@link int} for the amount of Jars required. + * @param output1 - The {@link ItemStack} which is a result of using the Oven. + * @param amount1 - An {@link int} for the amount of {@link output1} given. + * @param output2 - The {@link ItemStack} which is a filled Jar. + * @param amount2 - An {@link int} for the amount of {@link output2} given. + */ + private OvenRecipe( + final String oreDictSub, + final int jars, + final ItemStack output1, + final int amount1, + final ItemStack output2, + final int amount2) { + this(null, oreDictSub, jars, output1, amount1, output2, amount2); + } + + /** + * + * @param input1 - The {@link ItemStack} to be burned in the oven. + * @param jars - An {@link int} for the amount of Jars required. + * @param output1 - The {@link ItemStack} which is a result of using the Oven. + * @param amount1 - An {@link int} for the amount of {@link output1} given. + * @param output2 - The {@link ItemStack} which is a filled Jar. + * @param amount2 - An {@link int} for the amount of {@link output2} given. + */ + private OvenRecipe( + final ItemStack input1, + final int jars, + final ItemStack output1, + final int amount1, + final ItemStack output2, + final int amount2) { + this(input1, "", jars, output1, amount1, output2, amount2); + } + + /** + * + * @param input1 - The {@link ItemStack} to be burned in the oven. + * @param jars - An {@link int} for the amount of Jars required. + * @param output1 - The {@link ItemStack} which is a result of using the Oven. + * @param amount1 - An {@link int} for the amount of {@link output1} given. + * @param output2 - The {@link ItemStack} which is a filled Jar. + * @param amount2 - An {@link int} for the amount of {@link output2} given. + */ + private OvenRecipe( + final ItemStack input1, + String oreDict, + final int jars, + final ItemStack output1, + final int amount1, + final ItemStack output2, + final int amount2) { + this.inputs = input1; + this.validOreDictInput = oreDict; + this.jars = jars; + this.output = output1; + this.outputJar = output2; + this.outputAmount1 = amount1; + this.outputAmountJar = amount2; + Pair a1 = new Pair(output1, amount1); + Pair a2 = new Pair(output1, amount1); + this.outputs.put(a1); + this.outputs.put(a2); + } + + private boolean isInputMatch(final ItemStack intput1, int amt1) { + return (this.jars == 0 + || ((isMatch(intput1, this.inputs) && amt1 >= this.jars)) + || (!this.validOreDictInput.equals("") + && Utils.hasValidOreDictTag(this.validOreDictInput, intput1))); + } + + @SuppressWarnings("unused") + private boolean isMatch(final ItemStack output1, int amt1, final ItemStack output2, int amt2) { + return (this.jars == 0 + || ((amt1 == this.outputAmount1 && amt2 == this.outputAmountJar) + && (OvenRecipe.isMatch(output1, this.output) && OvenRecipe.isMatch(output2, outputJar)))); + } + + public static boolean isMatch(final ItemStack a, final ItemStack b) { + return (a == null && b == null) + || (a != null + && b != null + && a.getItem() == b.getItem() + && (!a.getHasSubtypes() || a.getItemDamage() == b.getItemDamage())); + } + + public static boolean isMatch(final ItemStack a, final ItemStack b, String oreName) { + return ((Utils.hasValidOreDictTag(oreName, a) && Utils.hasValidOreDictTag(oreName, b)) + || a == null && b == null) + || (a != null + && b != null + && a.getItem() == b.getItem() + && (!a.getHasSubtypes() || a.getItemDamage() == b.getItemDamage())); + } + + public int getJars() { + return this.jars; + } + + public ItemStack[] getOutputs() { + ItemStack x[] = new ItemStack[2]; + Pair a1 = outputs.get(0); + Pair a2 = outputs.get(1); + x[0] = Utils.getSimpleStack(a1.getKey(), a1.getValue()); + x[1] = Utils.getSimpleStack(a2.getKey(), a2.getValue()); + return x; + } + + public String getDescription() { + String[] y = new String[] { + "descriptor", + ("Input: " + (inputs != null ? this.inputs.getDisplayName() : "No Item") + " x" + + (inputs != null ? inputs.stackSize : 0)), + ("Jars Required: " + this.jars), + ("Output: " + (output != null ? this.output.getDisplayName() : "No Item") + " x" + + (output != null ? output.stackSize : 0)), + ("Jar Output: " + this.outputJar.getDisplayName() + " x" + jars), + ("OreDict: " + this.validOreDictInput) + }; + String z = ""; + for (String x : y) { + WitcheryExtras.log(0, x); + } + for (String x : y) { + z += "." + x; + } + return z; + } + + public boolean resultsIn(final ItemStack result) { + for (final ItemStack stack : getOutputs()) { + if (stack != null && stack.isItemEqual(result)) { + return true; + } + } + return false; + } + + public boolean uses(final ItemStack ingredient) { + if (this.inputs != null && this.inputs.isItemEqual(ingredient)) { + return true; + } + return Witchery.Items.GENERIC.itemEmptyClayJar.isMatch(ingredient) && this.jars > 0; + } + + public boolean isValid() { + return inputs != null && output != null; + } + } +} diff --git a/src/main/java/alkalus/main/core/entities/PredictionHandler.java b/src/main/java/alkalus/main/core/entities/PredictionHandler.java index e236251..11bd2c6 100644 --- a/src/main/java/alkalus/main/core/entities/PredictionHandler.java +++ b/src/main/java/alkalus/main/core/entities/PredictionHandler.java @@ -1,7 +1,9 @@ package alkalus.main.core.entities; -import java.lang.reflect.Field; - +import alkalus.main.api.RecipeManager; +import alkalus.main.asm.AsmConfig; +import alkalus.main.core.WitcheryExtras; +import alkalus.main.core.util.ReflectionUtils; import com.emoniph.witchery.predictions.Prediction; import com.emoniph.witchery.predictions.PredictionAlwaysForced; import com.emoniph.witchery.predictions.PredictionArrow; @@ -13,133 +15,178 @@ import com.emoniph.witchery.predictions.PredictionNetherTrip; import com.emoniph.witchery.predictions.PredictionRescue; import com.emoniph.witchery.predictions.PredictionWet; - -import alkalus.main.api.RecipeManager; -import alkalus.main.asm.AsmConfig; -import alkalus.main.core.WitcheryExtras; -import alkalus.main.core.util.ReflectionUtils; +import java.lang.reflect.Field; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; public class PredictionHandler { - // Base Prediction - private static final Field mSelfFulfillmentProbabilityPerSec; - - // Always Forced Prediction - private static final Field mRegularFulfillmentDurationInTicks; - private static final Field mRegularFulfillmentProbability; - - // Rescue Prediction - private static final Field mRescueEntityClass; - - // Buried Treasure - private static final Field mChestGenHook; - - // Multimine - private static final Field mBlock; - private static final Field mItem; - private static final Field mMinExtra; - private static final Field mMaxExtra; - - // Fight - private static final Field mFightEntityClass; - private static final Field mBindTameable; - - - static { - mSelfFulfillmentProbabilityPerSec = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.Prediction"), "selfFulfillmentProbabilityPerSec"); - mRegularFulfillmentDurationInTicks = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionAlwaysForced"), "regularFulfillmentDurationInTicks"); - mRegularFulfillmentProbability = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionAlwaysForced"), "regularFulfillmentProbability"); - mRescueEntityClass = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionRescue"), "entityClass"); - mChestGenHook = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionBuriedTreasure"), "chestGenHook"); - mBlock = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "block"); - mItem = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "itemPrototype"); - mMinExtra = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "minExtra"); - mMaxExtra = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "maxExtra"); - mFightEntityClass = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionFight"), "entityClass"); - mBindTameable = ReflectionUtils.getField(ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionFight"), "bindTameable"); - } - - public static void adjustPredictions() { - int[] aNewValues = new int[] { - AsmConfig.chancePredictionSpawnZombie, - AsmConfig.chancePredictionSpawnSkeleton, - AsmConfig.chancePredictionSpawnEnt, - AsmConfig.chancePredictionStumbleAndFall, - AsmConfig.chancePredictionExtraIron, - AsmConfig.chancePredictionFindShinies, - AsmConfig.chancePredictionFindShinies, - AsmConfig.chancePredictionSpawnBuriedTreasure, - AsmConfig.chancePredictionVillagerLove, - AsmConfig.chancePredictionSpawnBabaYagaBad, - AsmConfig.chancePredictionSpawnBabaYagaGood, - AsmConfig.chancePredictionSpawnFriendlyWolf, - AsmConfig.chancePredictionSpawnProtectiveAnimal, - AsmConfig.chancePredictionSpawnProtectiveAnimal, - AsmConfig.chancePredictionGetWet, - AsmConfig.chancePredictionTeleportNether, - AsmConfig.chancePredictionExtraCoal, - }; - for (int i=0;i<18;i++) { - Prediction aOld = RecipeManager.Predictions.getPrediction(i); - if (aOld != null) { - if (aOld.itemWeight != aNewValues[i-1]) { - RecipeManager.Predictions.remove(aOld); - WitcheryExtras.log(0, "Adjusting weight of "+aOld.getTranslationKey()+" from "+aOld.itemWeight+" to "+aNewValues[i-1]+"."); - RecipeManager.Predictions.add(generateNewPrediction(aOld, aNewValues[i-1])); - } - } - } - } - - - private static Prediction generateNewPrediction(Prediction aOldPrediction, int aNewWeight) { - Prediction aNewPrediction = null; - int predictionID = aOldPrediction.predictionID; - String translationKey = aOldPrediction.getTranslationKey(); - double selfFulfillmentProbabilityPerSec = (double) ReflectionUtils.getFieldValue(mSelfFulfillmentProbabilityPerSec, aOldPrediction); - if (aOldPrediction instanceof PredictionAlwaysForced) { - final int regularFulfillmentDurationInTicks = (int) ReflectionUtils.getFieldValue(mRegularFulfillmentDurationInTicks, aOldPrediction); - final double regularFulfillmentProbability = (double) ReflectionUtils.getFieldValue(mRegularFulfillmentProbability, aOldPrediction); - if (aOldPrediction instanceof PredictionMultiMine) { - final Block block = (Block) ReflectionUtils.getFieldValue(mBlock, aOldPrediction); - final ItemStack itemPrototype = (ItemStack) ReflectionUtils.getFieldValue(mItem, aOldPrediction); - final int minExtra = (int) ReflectionUtils.getFieldValue(mMinExtra, aOldPrediction); - final int maxExtra = (int) ReflectionUtils.getFieldValue(mMaxExtra, aOldPrediction); - aNewPrediction = new PredictionMultiMine(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey, regularFulfillmentDurationInTicks, regularFulfillmentProbability, block, itemPrototype, minExtra, maxExtra); - } - else if (aOldPrediction instanceof PredictionBuriedTreasure) { - final String chestGenHook = (String) ReflectionUtils.getFieldValue(mChestGenHook, aOldPrediction); - aNewPrediction = new PredictionBuriedTreasure(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey, regularFulfillmentDurationInTicks, regularFulfillmentProbability, chestGenHook); - } - else if (aOldPrediction instanceof PredictionFallInLove) { - aNewPrediction = new PredictionFallInLove(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey, regularFulfillmentDurationInTicks, regularFulfillmentProbability); - } - else if (aOldPrediction instanceof PredictionRescue) { - Class aEntityClass = (Class) ReflectionUtils.getFieldValue(mRescueEntityClass, aOldPrediction); - aNewPrediction = new PredictionRescue(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey, regularFulfillmentDurationInTicks, regularFulfillmentProbability, aEntityClass); - } - } - else if (aOldPrediction instanceof PredictionFight) { - Class aEntityClass = (Class) ReflectionUtils.getFieldValue(mFightEntityClass, aOldPrediction); - boolean aBindTameable = (boolean) ReflectionUtils.getFieldValue(mBindTameable, aOldPrediction); - aNewPrediction = new PredictionFight(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey, aEntityClass, aBindTameable); - } - else if (aOldPrediction instanceof PredictionArrow) { - aNewPrediction = new PredictionArrow(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); - } - else if (aOldPrediction instanceof PredictionFall) { - aNewPrediction = new PredictionFall(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); - } - else if (aOldPrediction instanceof PredictionWet) { - aNewPrediction = new PredictionWet(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); - } - else if (aOldPrediction instanceof PredictionNetherTrip) { - aNewPrediction = new PredictionNetherTrip(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); - } - - return aNewPrediction; - } - + // Base Prediction + private static final Field mSelfFulfillmentProbabilityPerSec; + + // Always Forced Prediction + private static final Field mRegularFulfillmentDurationInTicks; + private static final Field mRegularFulfillmentProbability; + + // Rescue Prediction + private static final Field mRescueEntityClass; + + // Buried Treasure + private static final Field mChestGenHook; + + // Multimine + private static final Field mBlock; + private static final Field mItem; + private static final Field mMinExtra; + private static final Field mMaxExtra; + + // Fight + private static final Field mFightEntityClass; + private static final Field mBindTameable; + + static { + mSelfFulfillmentProbabilityPerSec = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.Prediction"), + "selfFulfillmentProbabilityPerSec"); + mRegularFulfillmentDurationInTicks = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionAlwaysForced"), + "regularFulfillmentDurationInTicks"); + mRegularFulfillmentProbability = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionAlwaysForced"), + "regularFulfillmentProbability"); + mRescueEntityClass = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionRescue"), "entityClass"); + mChestGenHook = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionBuriedTreasure"), "chestGenHook"); + mBlock = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "block"); + mItem = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "itemPrototype"); + mMinExtra = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "minExtra"); + mMaxExtra = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionMultiMine"), "maxExtra"); + mFightEntityClass = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionFight"), "entityClass"); + mBindTameable = ReflectionUtils.getField( + ReflectionUtils.getClass("com.emoniph.witchery.predictions.PredictionFight"), "bindTameable"); + } + + public static void adjustPredictions() { + int[] aNewValues = new int[] { + AsmConfig.chancePredictionSpawnZombie, + AsmConfig.chancePredictionSpawnSkeleton, + AsmConfig.chancePredictionSpawnEnt, + AsmConfig.chancePredictionStumbleAndFall, + AsmConfig.chancePredictionExtraIron, + AsmConfig.chancePredictionFindShinies, + AsmConfig.chancePredictionFindShinies, + AsmConfig.chancePredictionSpawnBuriedTreasure, + AsmConfig.chancePredictionVillagerLove, + AsmConfig.chancePredictionSpawnBabaYagaBad, + AsmConfig.chancePredictionSpawnBabaYagaGood, + AsmConfig.chancePredictionSpawnFriendlyWolf, + AsmConfig.chancePredictionSpawnProtectiveAnimal, + AsmConfig.chancePredictionSpawnProtectiveAnimal, + AsmConfig.chancePredictionGetWet, + AsmConfig.chancePredictionTeleportNether, + AsmConfig.chancePredictionExtraCoal, + }; + for (int i = 0; i < 18; i++) { + Prediction aOld = RecipeManager.Predictions.getPrediction(i); + if (aOld != null) { + if (aOld.itemWeight != aNewValues[i - 1]) { + RecipeManager.Predictions.remove(aOld); + WitcheryExtras.log( + 0, + "Adjusting weight of " + aOld.getTranslationKey() + " from " + aOld.itemWeight + " to " + + aNewValues[i - 1] + "."); + RecipeManager.Predictions.add(generateNewPrediction(aOld, aNewValues[i - 1])); + } + } + } + } + + private static Prediction generateNewPrediction(Prediction aOldPrediction, int aNewWeight) { + Prediction aNewPrediction = null; + int predictionID = aOldPrediction.predictionID; + String translationKey = aOldPrediction.getTranslationKey(); + double selfFulfillmentProbabilityPerSec = + (double) ReflectionUtils.getFieldValue(mSelfFulfillmentProbabilityPerSec, aOldPrediction); + if (aOldPrediction instanceof PredictionAlwaysForced) { + final int regularFulfillmentDurationInTicks = + (int) ReflectionUtils.getFieldValue(mRegularFulfillmentDurationInTicks, aOldPrediction); + final double regularFulfillmentProbability = + (double) ReflectionUtils.getFieldValue(mRegularFulfillmentProbability, aOldPrediction); + if (aOldPrediction instanceof PredictionMultiMine) { + final Block block = (Block) ReflectionUtils.getFieldValue(mBlock, aOldPrediction); + final ItemStack itemPrototype = (ItemStack) ReflectionUtils.getFieldValue(mItem, aOldPrediction); + final int minExtra = (int) ReflectionUtils.getFieldValue(mMinExtra, aOldPrediction); + final int maxExtra = (int) ReflectionUtils.getFieldValue(mMaxExtra, aOldPrediction); + aNewPrediction = new PredictionMultiMine( + predictionID, + aNewWeight, + selfFulfillmentProbabilityPerSec, + translationKey, + regularFulfillmentDurationInTicks, + regularFulfillmentProbability, + block, + itemPrototype, + minExtra, + maxExtra); + } else if (aOldPrediction instanceof PredictionBuriedTreasure) { + final String chestGenHook = (String) ReflectionUtils.getFieldValue(mChestGenHook, aOldPrediction); + aNewPrediction = new PredictionBuriedTreasure( + predictionID, + aNewWeight, + selfFulfillmentProbabilityPerSec, + translationKey, + regularFulfillmentDurationInTicks, + regularFulfillmentProbability, + chestGenHook); + } else if (aOldPrediction instanceof PredictionFallInLove) { + aNewPrediction = new PredictionFallInLove( + predictionID, + aNewWeight, + selfFulfillmentProbabilityPerSec, + translationKey, + regularFulfillmentDurationInTicks, + regularFulfillmentProbability); + } else if (aOldPrediction instanceof PredictionRescue) { + Class aEntityClass = (Class) ReflectionUtils.getFieldValue(mRescueEntityClass, aOldPrediction); + aNewPrediction = new PredictionRescue( + predictionID, + aNewWeight, + selfFulfillmentProbabilityPerSec, + translationKey, + regularFulfillmentDurationInTicks, + regularFulfillmentProbability, + aEntityClass); + } + } else if (aOldPrediction instanceof PredictionFight) { + Class aEntityClass = (Class) ReflectionUtils.getFieldValue(mFightEntityClass, aOldPrediction); + boolean aBindTameable = (boolean) ReflectionUtils.getFieldValue(mBindTameable, aOldPrediction); + aNewPrediction = new PredictionFight( + predictionID, + aNewWeight, + selfFulfillmentProbabilityPerSec, + translationKey, + aEntityClass, + aBindTameable); + } else if (aOldPrediction instanceof PredictionArrow) { + aNewPrediction = + new PredictionArrow(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); + } else if (aOldPrediction instanceof PredictionFall) { + aNewPrediction = + new PredictionFall(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); + } else if (aOldPrediction instanceof PredictionWet) { + aNewPrediction = + new PredictionWet(predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); + } else if (aOldPrediction instanceof PredictionNetherTrip) { + aNewPrediction = new PredictionNetherTrip( + predictionID, aNewWeight, selfFulfillmentProbabilityPerSec, translationKey); + } + + return aNewPrediction; + } } diff --git a/src/main/java/alkalus/main/core/proxy/Proxy_Client.java b/src/main/java/alkalus/main/core/proxy/Proxy_Client.java index a748eeb..c0294f3 100644 --- a/src/main/java/alkalus/main/core/proxy/Proxy_Client.java +++ b/src/main/java/alkalus/main/core/proxy/Proxy_Client.java @@ -6,24 +6,18 @@ public class Proxy_Client extends Proxy_Common { - public void preInit(final FMLPreInitializationEvent e) { - super.preInit(e); - - } + public void preInit(final FMLPreInitializationEvent e) { + super.preInit(e); + } - public void init(final FMLInitializationEvent e) { - super.init(e); - - } + public void init(final FMLInitializationEvent e) { + super.init(e); + } - public void postInit(final FMLPostInitializationEvent e) { - super.postInit(e); - - } - - @Override - public void registerRenderers() { - - } - + public void postInit(final FMLPostInitializationEvent e) { + super.postInit(e); + } + + @Override + public void registerRenderers() {} } diff --git a/src/main/java/alkalus/main/core/proxy/Proxy_Common.java b/src/main/java/alkalus/main/core/proxy/Proxy_Common.java index 2a18036..d5c0e92 100644 --- a/src/main/java/alkalus/main/core/proxy/Proxy_Common.java +++ b/src/main/java/alkalus/main/core/proxy/Proxy_Common.java @@ -8,21 +8,16 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; public class Proxy_Common { - - public void preInit(final FMLPreInitializationEvent e) { - - } - public void init(final FMLInitializationEvent e) { - new CustomRecipeLoader(); - } + public void preInit(final FMLPreInitializationEvent e) {} - public synchronized void postInit(final FMLPostInitializationEvent e) { - Utils.registerEvent(new TooltipHandler()); - } + public void init(final FMLInitializationEvent e) { + new CustomRecipeLoader(); + } - public void registerRenderers() { - - } - + public synchronized void postInit(final FMLPostInitializationEvent e) { + Utils.registerEvent(new TooltipHandler()); + } + + public void registerRenderers() {} } diff --git a/src/main/java/alkalus/main/core/proxy/Proxy_Server.java b/src/main/java/alkalus/main/core/proxy/Proxy_Server.java index 06365fa..b01ea1e 100644 --- a/src/main/java/alkalus/main/core/proxy/Proxy_Server.java +++ b/src/main/java/alkalus/main/core/proxy/Proxy_Server.java @@ -4,18 +4,17 @@ import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; -public class Proxy_Server extends Proxy_Common{ +public class Proxy_Server extends Proxy_Common { - public void preInit(final FMLPreInitializationEvent e) { - super.preInit(e); - } + public void preInit(final FMLPreInitializationEvent e) { + super.preInit(e); + } - public void init(final FMLInitializationEvent e) { - super.init(e); - } + public void init(final FMLInitializationEvent e) { + super.init(e); + } - public void postInit(final FMLPostInitializationEvent e) { - super.postInit(e); - } - + public void postInit(final FMLPostInitializationEvent e) { + super.postInit(e); + } } diff --git a/src/main/java/alkalus/main/core/recipe/CustomRecipeLoader.java b/src/main/java/alkalus/main/core/recipe/CustomRecipeLoader.java index 70feeb5..9106b48 100644 --- a/src/main/java/alkalus/main/core/recipe/CustomRecipeLoader.java +++ b/src/main/java/alkalus/main/core/recipe/CustomRecipeLoader.java @@ -5,17 +5,13 @@ public class CustomRecipeLoader { - public CustomRecipeLoader() { - run(); - } - - private final void run() { - //Fixes recipes that hardcode Witchery Garlic types. - new GarlicRecipes(); - OvenRecipes.generateDefaultOvenRecipes(); - - } + public CustomRecipeLoader() { + run(); + } - - + private final void run() { + // Fixes recipes that hardcode Witchery Garlic types. + new GarlicRecipes(); + OvenRecipes.generateDefaultOvenRecipes(); + } } diff --git a/src/main/java/alkalus/main/core/recipe/fixes/GarlicRecipes.java b/src/main/java/alkalus/main/core/recipe/fixes/GarlicRecipes.java index f393460..cd7011e 100644 --- a/src/main/java/alkalus/main/core/recipe/fixes/GarlicRecipes.java +++ b/src/main/java/alkalus/main/core/recipe/fixes/GarlicRecipes.java @@ -1,53 +1,78 @@ package alkalus.main.core.recipe.fixes; +import alkalus.main.core.WitcheryExtras; +import alkalus.main.core.util.Utils; import com.emoniph.witchery.Witchery; - import cpw.mods.fml.common.registry.GameRegistry; - import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; -import alkalus.main.core.WitcheryExtras; -import alkalus.main.core.util.Utils; - public class GarlicRecipes { - private final ItemStack mGarlics[]; - - public GarlicRecipes() { - WitcheryExtras.log(0, "Attempting to fix Witchery recipes that don't use OreDict for Garlic."); - mGarlics = Utils.getAllItemsFromOreDictEntry("cropGarlic"); - fixGarlicArmour(); - fixVampireBook(); - } - - private void fixGarlicArmour() { - Item[][] hunterItemsSilvered = { { Witchery.Items.HUNTER_BOOTS_SILVERED, Witchery.Items.HUNTER_BOOTS_GARLICKED }, { Witchery.Items.HUNTER_LEGS_SILVERED, Witchery.Items.HUNTER_LEGS_GARLICKED }, { Witchery.Items.HUNTER_COAT_SILVERED, Witchery.Items.HUNTER_COAT_GARLICKED }, { Witchery.Items.HUNTER_HAT_SILVERED, Witchery.Items.HUNTER_HAT_GARLICKED } }; - for (int i = 0; i < hunterItemsSilvered.length; i++) { - ItemStack currentStack = new ItemStack(hunterItemsSilvered[i][1]); - if (Utils.removeAllCraftingRecipesByOutputItem(currentStack)) { - WitcheryExtras.log(1, "Successfully removed all crafting recipes for "+currentStack.getDisplayName()+"."); - } - for (ItemStack garlic : mGarlics) { - CraftingManager.getInstance().addRecipe(currentStack, new Object[] { " g ", "g#g", " s ", Character.valueOf('#'), new ItemStack(hunterItemsSilvered[i][0]), Character.valueOf('s'), new ItemStack(Items.string), Character.valueOf('g'), garlic.copy()}).func_92100_c(); - } - } - WitcheryExtras.log(0, "Fixed Recipes for Witchery Armours."); - } - - private void fixVampireBook() { - ItemStack currentStack = new ItemStack(Witchery.Items.VAMPIRE_BOOK); - if (Utils.removeAllCraftingRecipesByOutputItem(currentStack)) { - WitcheryExtras.log(1, "Successfully removed all crafting recipes for "+currentStack.getDisplayName()+"."); - } - for (ItemStack garlic : mGarlics) { - GameRegistry.addShapedRecipe(currentStack, new Object[] { "#s#", "#b#", "#g#", Character.valueOf('s'), new ItemStack(Items.nether_star), Character.valueOf('b'), new ItemStack(Items.book), Character.valueOf('g'), garlic.copy(), Character.valueOf('#'), new ItemStack(Items.nether_wart) }); - } - WitcheryExtras.log(0, "Fixed recipe for the Vampire Book."); - } + private final ItemStack mGarlics[]; + public GarlicRecipes() { + WitcheryExtras.log(0, "Attempting to fix Witchery recipes that don't use OreDict for Garlic."); + mGarlics = Utils.getAllItemsFromOreDictEntry("cropGarlic"); + fixGarlicArmour(); + fixVampireBook(); + } + private void fixGarlicArmour() { + Item[][] hunterItemsSilvered = { + {Witchery.Items.HUNTER_BOOTS_SILVERED, Witchery.Items.HUNTER_BOOTS_GARLICKED}, + {Witchery.Items.HUNTER_LEGS_SILVERED, Witchery.Items.HUNTER_LEGS_GARLICKED}, + {Witchery.Items.HUNTER_COAT_SILVERED, Witchery.Items.HUNTER_COAT_GARLICKED}, + {Witchery.Items.HUNTER_HAT_SILVERED, Witchery.Items.HUNTER_HAT_GARLICKED} + }; + for (int i = 0; i < hunterItemsSilvered.length; i++) { + ItemStack currentStack = new ItemStack(hunterItemsSilvered[i][1]); + if (Utils.removeAllCraftingRecipesByOutputItem(currentStack)) { + WitcheryExtras.log( + 1, "Successfully removed all crafting recipes for " + currentStack.getDisplayName() + "."); + } + for (ItemStack garlic : mGarlics) { + CraftingManager.getInstance() + .addRecipe(currentStack, new Object[] { + " g ", + "g#g", + " s ", + Character.valueOf('#'), + new ItemStack(hunterItemsSilvered[i][0]), + Character.valueOf('s'), + new ItemStack(Items.string), + Character.valueOf('g'), + garlic.copy() + }) + .func_92100_c(); + } + } + WitcheryExtras.log(0, "Fixed Recipes for Witchery Armours."); + } + private void fixVampireBook() { + ItemStack currentStack = new ItemStack(Witchery.Items.VAMPIRE_BOOK); + if (Utils.removeAllCraftingRecipesByOutputItem(currentStack)) { + WitcheryExtras.log( + 1, "Successfully removed all crafting recipes for " + currentStack.getDisplayName() + "."); + } + for (ItemStack garlic : mGarlics) { + GameRegistry.addShapedRecipe(currentStack, new Object[] { + "#s#", + "#b#", + "#g#", + Character.valueOf('s'), + new ItemStack(Items.nether_star), + Character.valueOf('b'), + new ItemStack(Items.book), + Character.valueOf('g'), + garlic.copy(), + Character.valueOf('#'), + new ItemStack(Items.nether_wart) + }); + } + WitcheryExtras.log(0, "Fixed recipe for the Vampire Book."); + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_Cauldron.java b/src/main/java/alkalus/main/core/types/Witchery_Cauldron.java index 9613385..04605fe 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_Cauldron.java +++ b/src/main/java/alkalus/main/core/types/Witchery_Cauldron.java @@ -1,16 +1,14 @@ package alkalus.main.core.types; -import java.util.Hashtable; -import java.util.List; - +import alkalus.main.core.util.ReflectionUtils; import com.emoniph.witchery.brewing.BrewItemKey; import com.emoniph.witchery.brewing.WitcheryBrewRegistry; import com.emoniph.witchery.brewing.action.BrewAction; import com.emoniph.witchery.brewing.action.BrewActionRitualRecipe; import com.emoniph.witchery.crafting.DistilleryRecipes; import com.emoniph.witchery.crafting.DistilleryRecipes.DistilleryRecipe; - -import alkalus.main.core.util.ReflectionUtils; +import java.util.Hashtable; +import java.util.List; import net.minecraft.item.ItemStack; public class Witchery_Cauldron { @@ -18,65 +16,51 @@ public class Witchery_Cauldron { public static List getRecipes() { return WitcheryBrewRegistry.INSTANCE.getRecipes(); } - + public static Hashtable getIngredients() { - return (Hashtable) ReflectionUtils.getFieldValue(ReflectionUtils.getField(WitcheryBrewRegistry.class, "ingredients"), WitcheryBrewRegistry.INSTANCE); + return (Hashtable) ReflectionUtils.getFieldValue( + ReflectionUtils.getField(WitcheryBrewRegistry.class, "ingredients"), WitcheryBrewRegistry.INSTANCE); } - + public BrewAction getActionForItemStack(final ItemStack stack) { return getIngredients().get(BrewItemKey.fromStack(stack)); - } - + } private boolean removeCauldronBrewAction(final ItemStack ingredient) { - return removeCauldronBrewAction(getActionForItemStack(ingredient)); + return removeCauldronBrewAction(getActionForItemStack(ingredient)); } - - + private boolean removeCauldronBrewAction(final BrewAction ingredient) { - // Bad Recipe to remove - if (ingredient == null || ingredient.ITEM_KEY == null) { - return false; - } + // Bad Recipe to remove + if (ingredient == null || ingredient.ITEM_KEY == null) { + return false; + } if (getIngredients().containsKey(ingredient.ITEM_KEY)) { - if (getIngredients().remove(ingredient.ITEM_KEY) != null) { - return true; - } + if (getIngredients().remove(ingredient.ITEM_KEY) != null) { + return true; + } } return false; } - + public static synchronized BrewActionRitualRecipe findRecipeForOutput(ItemStack aOutput) { - for (BrewActionRitualRecipe aRecipe : getRecipes()) { - if (aRecipe != null) { - - } - } - - - return null; + for (BrewActionRitualRecipe aRecipe : getRecipes()) { + if (aRecipe != null) {} + } + + return null; } - - - - - - - - - - - - public static synchronized DistilleryRecipe getDistillingResult(ItemStack input1, ItemStack intput2, ItemStack jars){ - return DistilleryRecipes.instance().getDistillingResult(input1, intput2, jars); - } - public static synchronized DistilleryRecipe findRecipeFor(ItemStack result){ - return DistilleryRecipes.instance().findRecipeFor(result); - } + public static synchronized DistilleryRecipe getDistillingResult( + ItemStack input1, ItemStack intput2, ItemStack jars) { + return DistilleryRecipes.instance().getDistillingResult(input1, intput2, jars); + } - public static synchronized DistilleryRecipe findRecipeUsing(ItemStack ingredient){ - return DistilleryRecipes.instance().findRecipeUsing(ingredient); - } + public static synchronized DistilleryRecipe findRecipeFor(ItemStack result) { + return DistilleryRecipes.instance().findRecipeFor(result); + } + public static synchronized DistilleryRecipe findRecipeUsing(ItemStack ingredient) { + return DistilleryRecipes.instance().findRecipeUsing(ingredient); + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_CreaturePower.java b/src/main/java/alkalus/main/core/types/Witchery_CreaturePower.java index 4bf8c89..691ee2d 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_CreaturePower.java +++ b/src/main/java/alkalus/main/core/types/Witchery_CreaturePower.java @@ -1,68 +1,66 @@ package alkalus.main.core.types; +import alkalus.main.core.util.ReflectionUtils; +import com.emoniph.witchery.infusion.infusions.creature.CreaturePower; import java.util.ArrayList; +import net.minecraft.entity.EntityLiving; -import com.emoniph.witchery.infusion.infusions.creature.CreaturePower; +public class Witchery_CreaturePower { -import net.minecraft.entity.EntityLiving; + /** + * + * @param creatureType - An Entity that Extends EntityLiving. + * @return - CreaturePower object. + */ + public static synchronized CreaturePower createNewCreaturePower(final Class creatureType) { + CreaturePower h = new CreaturePower(getLastUsedCreaturePowerID() + 1, creatureType); + return h != null ? h : null; + } -import alkalus.main.core.util.ReflectionUtils; + /** + * + * @param mID - The Unique ID for this new CreaturePower + * @param creatureType - An Entity that Extends EntityLiving. + * @return - CreaturePower object. + */ + public static synchronized CreaturePower createNewCreaturePower( + final int mID, final Class creatureType) { + CreaturePower h = new CreaturePower(mID, creatureType); + return h != null ? h : null; + } -public class Witchery_CreaturePower { + private static int mCachedLastRegistryValue; + + @SuppressWarnings("unchecked") + public static synchronized int getLastUsedCreaturePowerID() { + Object f = ReflectionUtils.getField(CreaturePower.Registry.instance(), "registry"); + ArrayList registry; + try { + if (f != null) { + registry = (ArrayList) f; + if (registry != null) { + return mCachedLastRegistryValue = registry.size(); + } + } + } catch (Throwable t) { + } + return mCachedLastRegistryValue + 1; + } - /** - * - * @param creatureType - An Entity that Extends EntityLiving. - * @return - CreaturePower object. - */ - public static synchronized CreaturePower createNewCreaturePower(final Class creatureType) { - CreaturePower h = new CreaturePower(getLastUsedCreaturePowerID()+1, creatureType); - return h != null ? h : null; - } - - /** - * - * @param mID - The Unique ID for this new CreaturePower - * @param creatureType - An Entity that Extends EntityLiving. - * @return - CreaturePower object. - */ - public static synchronized CreaturePower createNewCreaturePower(final int mID, final Class creatureType) { - CreaturePower h = new CreaturePower(mID, creatureType); - return h != null ? h : null; - } - - private static int mCachedLastRegistryValue; - @SuppressWarnings("unchecked") - public static synchronized int getLastUsedCreaturePowerID() { - Object f = ReflectionUtils.getField(CreaturePower.Registry.instance(), "registry"); - ArrayList registry; - try { - if (f != null) { - registry = (ArrayList) f; - if (registry != null) { - return mCachedLastRegistryValue = registry.size(); - } - } - } - catch (Throwable t) {} - return mCachedLastRegistryValue+1; - } - - /** - * - * @param entity - The Entity to find a CreaturePower for. - * @return - */ - public static synchronized CreaturePower getCreaturePower(EntityLiving entity) { - return CreaturePower.Registry.instance().get(entity); - } - /** - * - * @param entity - The Entity ID to use to find a CreaturePower. - * @return - */ - public static synchronized CreaturePower getCreaturePower(int entityID) { - return CreaturePower.Registry.instance().get(entityID); - } - + /** + * + * @param entity - The Entity to find a CreaturePower for. + * @return + */ + public static synchronized CreaturePower getCreaturePower(EntityLiving entity) { + return CreaturePower.Registry.instance().get(entity); + } + /** + * + * @param entity - The Entity ID to use to find a CreaturePower. + * @return + */ + public static synchronized CreaturePower getCreaturePower(int entityID) { + return CreaturePower.Registry.instance().get(entityID); + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_Distillery.java b/src/main/java/alkalus/main/core/types/Witchery_Distillery.java index 855af6f..1e301aa 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_Distillery.java +++ b/src/main/java/alkalus/main/core/types/Witchery_Distillery.java @@ -1,23 +1,22 @@ package alkalus.main.core.types; -import java.util.ArrayList; -import java.util.List; - import com.emoniph.witchery.crafting.DistilleryRecipes; import com.emoniph.witchery.crafting.DistilleryRecipes.DistilleryRecipe; - +import java.util.ArrayList; +import java.util.List; import net.minecraft.item.ItemStack; public class Witchery_Distillery { - public static synchronized DistilleryRecipe getDistillingResult(ItemStack input1, ItemStack intput2, ItemStack jars){ - return DistilleryRecipes.instance().getDistillingResult(input1, intput2, jars); - } + public static synchronized DistilleryRecipe getDistillingResult( + ItemStack input1, ItemStack intput2, ItemStack jars) { + return DistilleryRecipes.instance().getDistillingResult(input1, intput2, jars); + } + + public static synchronized DistilleryRecipe findRecipeFor(ItemStack result) { + return DistilleryRecipes.instance().findRecipeFor(result); + } - public static synchronized DistilleryRecipe findRecipeFor(ItemStack result){ - return DistilleryRecipes.instance().findRecipeFor(result); - } - public static synchronized List findRecipesFor(ItemStack result) { List recipes = new ArrayList<>(); for (DistilleryRecipes.DistilleryRecipe recipe : DistilleryRecipes.instance().recipes) { @@ -28,8 +27,7 @@ public static synchronized List findRecipesF return recipes; } - public static synchronized DistilleryRecipe findRecipeUsing(ItemStack ingredient){ - return DistilleryRecipes.instance().findRecipeUsing(ingredient); - } - + public static synchronized DistilleryRecipe findRecipeUsing(ItemStack ingredient) { + return DistilleryRecipes.instance().findRecipeUsing(ingredient); + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_Infusion.java b/src/main/java/alkalus/main/core/types/Witchery_Infusion.java index 2468407..93f5a0d 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_Infusion.java +++ b/src/main/java/alkalus/main/core/types/Witchery_Infusion.java @@ -1,66 +1,61 @@ package alkalus.main.core.types; +import alkalus.main.core.util.ReflectionUtils; +import com.emoniph.witchery.infusion.Infusion; import java.util.ArrayList; +import net.minecraft.entity.player.EntityPlayer; -import com.emoniph.witchery.infusion.Infusion; -import com.emoniph.witchery.infusion.infusions.creature.CreaturePower; +public class Witchery_Infusion { -import net.minecraft.entity.EntityLiving; -import net.minecraft.entity.player.EntityPlayer; + /** + * + * @return - Infusion object. + */ + public static synchronized Infusion createNewInfusion() { + return createNewInfusion(getLastUsedInfusionID() + 1); + } -import alkalus.main.core.util.ReflectionUtils; + /** + * + * @param mID - The Unique ID for this new Infusion + * @return - Infusion object. + */ + public static synchronized Infusion createNewInfusion(final int mID) { + Infusion h = new Infusion(mID); + return h != null ? h : null; + } -public class Witchery_Infusion { + private static int mCachedLastRegistryValue; + + public static synchronized int getLastUsedInfusionID() { + Object f = ReflectionUtils.getField(Infusion.Registry.instance(), "registry"); + ArrayList registry; + try { + if (f != null) { + registry = (ArrayList) f; + if (registry != null) { + return mCachedLastRegistryValue = registry.size(); + } + } + } catch (Throwable t) { + } + return mCachedLastRegistryValue + 1; + } - /** - * - * @return - Infusion object. - */ - public static synchronized Infusion createNewInfusion() { - return createNewInfusion(getLastUsedInfusionID()+1); - } - - /** - * - * @param mID - The Unique ID for this new Infusion - * @return - Infusion object. - */ - public static synchronized Infusion createNewInfusion(final int mID) { - Infusion h = new Infusion(mID); - return h != null ? h : null; - } - - private static int mCachedLastRegistryValue; - public static synchronized int getLastUsedInfusionID() { - Object f = ReflectionUtils.getField(Infusion.Registry.instance(), "registry"); - ArrayList registry; - try { - if (f != null) { - registry = (ArrayList) f; - if (registry != null) { - return mCachedLastRegistryValue = registry.size(); - } - } - } - catch (Throwable t) {} - return mCachedLastRegistryValue+1; - } - - /** - * - * @param entity - The Player to find a Infusion for. - * @return - */ - public static synchronized Infusion getInfusionOnPlayer(EntityPlayer entity) { - return Infusion.Registry.instance().get(entity); - } - /** - * - * @param entity - The Infusion ID to use to find an Infusion. - * @return - */ - public static synchronized Infusion getInfusion(int infusionID) { - return Infusion.Registry.instance().get(infusionID); - } - + /** + * + * @param entity - The Player to find a Infusion for. + * @return + */ + public static synchronized Infusion getInfusionOnPlayer(EntityPlayer entity) { + return Infusion.Registry.instance().get(entity); + } + /** + * + * @param entity - The Infusion ID to use to find an Infusion. + * @return + */ + public static synchronized Infusion getInfusion(int infusionID) { + return Infusion.Registry.instance().get(infusionID); + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_Kettle.java b/src/main/java/alkalus/main/core/types/Witchery_Kettle.java index 9b1c3e5..9172a84 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_Kettle.java +++ b/src/main/java/alkalus/main/core/types/Witchery_Kettle.java @@ -1,53 +1,51 @@ package alkalus.main.core.types; -import java.util.ArrayList; - +import alkalus.main.core.util.AutoMap; import com.emoniph.witchery.crafting.KettleRecipes; import com.emoniph.witchery.crafting.KettleRecipes.KettleRecipe; - +import java.util.ArrayList; import net.minecraft.item.ItemStack; -import alkalus.main.core.util.AutoMap; - public class Witchery_Kettle { - public static AutoMap findRecipesFor(final ItemStack result) { - AutoMap recipesOld = new AutoMap(); - ArrayList recipes = new ArrayList(); - recipes = KettleRecipes.instance().recipes; - for (final KettleRecipe recipe : recipes) { - if (recipe.output.isItemEqual(result)) { - recipesOld.put(recipe); - } - } - return recipesOld; - } - - public static KettleRecipe findRecipeWithSomeInputsAndAnOutput(ItemStack[] inputs, ItemStack output) { - if (inputs == null || inputs.length < 1 || output == null) { - return null; - } - AutoMap recipesWithMatchingOutput = findRecipesFor(output); - AutoMap mMatchingItems = new AutoMap(); - KettleRecipe result = null; - //Cycle Recipes - loop1: for (KettleRecipe K : recipesWithMatchingOutput) { - //Cycle through inputs we're searching for to match - loop2: for (ItemStack M : inputs) { - //Cycle through the recipes inputs - for (ItemStack I : K.inputs) { - if (I.isItemEqual(M)) { - mMatchingItems.put(M); - continue loop2; - } - } - } - if (mMatchingItems.size() >= (Math.max(1, inputs.length-1))) { - result = K; - break loop1; - } - } - return result; - } - + public static AutoMap findRecipesFor(final ItemStack result) { + AutoMap recipesOld = new AutoMap(); + ArrayList recipes = new ArrayList(); + recipes = KettleRecipes.instance().recipes; + for (final KettleRecipe recipe : recipes) { + if (recipe.output.isItemEqual(result)) { + recipesOld.put(recipe); + } + } + return recipesOld; + } + + public static KettleRecipe findRecipeWithSomeInputsAndAnOutput(ItemStack[] inputs, ItemStack output) { + if (inputs == null || inputs.length < 1 || output == null) { + return null; + } + AutoMap recipesWithMatchingOutput = findRecipesFor(output); + AutoMap mMatchingItems = new AutoMap(); + KettleRecipe result = null; + // Cycle Recipes + loop1: + for (KettleRecipe K : recipesWithMatchingOutput) { + // Cycle through inputs we're searching for to match + loop2: + for (ItemStack M : inputs) { + // Cycle through the recipes inputs + for (ItemStack I : K.inputs) { + if (I.isItemEqual(M)) { + mMatchingItems.put(M); + continue loop2; + } + } + } + if (mMatchingItems.size() >= (Math.max(1, inputs.length - 1))) { + result = K; + break loop1; + } + } + return result; + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_Oven.java b/src/main/java/alkalus/main/core/types/Witchery_Oven.java index 6ec4379..f0d362d 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_Oven.java +++ b/src/main/java/alkalus/main/core/types/Witchery_Oven.java @@ -6,16 +6,15 @@ public class Witchery_Oven { - public static synchronized OvenRecipe getOvenResult(final ItemStack input1, final int jars){ - return OvenRecipes.getOvenResult(input1, jars); - } + public static synchronized OvenRecipe getOvenResult(final ItemStack input1, final int jars) { + return OvenRecipes.getOvenResult(input1, jars); + } - public static synchronized OvenRecipe findRecipeFor(ItemStack result){ - return OvenRecipes.findRecipeFor(result); - } - - public static synchronized OvenRecipe findRecipeUsing(ItemStack ingredient){ - return OvenRecipes.findRecipeUsing(ingredient); - } + public static synchronized OvenRecipe findRecipeFor(ItemStack result) { + return OvenRecipes.findRecipeFor(result); + } + public static synchronized OvenRecipe findRecipeUsing(ItemStack ingredient) { + return OvenRecipes.findRecipeUsing(ingredient); + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_Predictions.java b/src/main/java/alkalus/main/core/types/Witchery_Predictions.java index 8ce5f1f..a69ca3b 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_Predictions.java +++ b/src/main/java/alkalus/main/core/types/Witchery_Predictions.java @@ -1,27 +1,25 @@ package alkalus.main.core.types; -import java.util.Hashtable; - +import alkalus.main.core.util.ReflectionUtils; import com.emoniph.witchery.predictions.Prediction; import com.emoniph.witchery.predictions.PredictionManager; -import alkalus.main.core.util.ReflectionUtils; +import java.util.Hashtable; public class Witchery_Predictions { - - @SuppressWarnings("unchecked") - public static synchronized Hashtable getPredictions() { - Object f = ReflectionUtils.getField(PredictionManager.instance(), "predictions"); - Hashtable registry; - try { - if (f != null) { - registry = (Hashtable) f; - if (registry != null) { - return registry; - } - } - } - catch (Throwable t) {} - return new Hashtable(); - } - + + @SuppressWarnings("unchecked") + public static synchronized Hashtable getPredictions() { + Object f = ReflectionUtils.getField(PredictionManager.instance(), "predictions"); + Hashtable registry; + try { + if (f != null) { + registry = (Hashtable) f; + if (registry != null) { + return registry; + } + } + } catch (Throwable t) { + } + return new Hashtable(); + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_Rite.java b/src/main/java/alkalus/main/core/types/Witchery_Rite.java index 7347630..e654a41 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_Rite.java +++ b/src/main/java/alkalus/main/core/types/Witchery_Rite.java @@ -1,28 +1,26 @@ package alkalus.main.core.types; -import java.util.ArrayList; - +import alkalus.main.core.util.ReflectionUtils; import com.emoniph.witchery.ritual.RiteRegistry; import com.emoniph.witchery.ritual.RiteRegistry.Ritual; - -import alkalus.main.core.util.ReflectionUtils; +import java.util.ArrayList; public class Witchery_Rite { - - private static int mCachedLastRegistryValue; - public static synchronized int getLastUsedRiteID() { - Object f = ReflectionUtils.getField(RiteRegistry.instance(), "rituals"); - ArrayList registry; - try { - if (f != null) { - registry = (ArrayList) f; - if (registry != null) { - return mCachedLastRegistryValue = registry.size(); - } - } - } - catch (Throwable t) {} - return mCachedLastRegistryValue+1; - } - + + private static int mCachedLastRegistryValue; + + public static synchronized int getLastUsedRiteID() { + Object f = ReflectionUtils.getField(RiteRegistry.instance(), "rituals"); + ArrayList registry; + try { + if (f != null) { + registry = (ArrayList) f; + if (registry != null) { + return mCachedLastRegistryValue = registry.size(); + } + } + } catch (Throwable t) { + } + return mCachedLastRegistryValue + 1; + } } diff --git a/src/main/java/alkalus/main/core/types/Witchery_SpinningWheel.java b/src/main/java/alkalus/main/core/types/Witchery_SpinningWheel.java index e5c5839..92af70f 100644 --- a/src/main/java/alkalus/main/core/types/Witchery_SpinningWheel.java +++ b/src/main/java/alkalus/main/core/types/Witchery_SpinningWheel.java @@ -2,25 +2,23 @@ import com.emoniph.witchery.crafting.SpinningRecipes; import com.emoniph.witchery.crafting.SpinningRecipes.SpinningRecipe; - import net.minecraft.item.ItemStack; public class Witchery_SpinningWheel { - public static synchronized SpinningRecipe getRecipe(ItemStack fibre, ItemStack[] modifiers) { - return SpinningRecipes.instance().getRecipe(fibre, modifiers); - } - - public static synchronized SpinningRecipe findRecipeFor(ItemStack result) { - return SpinningRecipes.instance().findRecipeFor(result); - } + public static synchronized SpinningRecipe getRecipe(ItemStack fibre, ItemStack[] modifiers) { + return SpinningRecipes.instance().getRecipe(fibre, modifiers); + } - public static synchronized SpinningRecipe findRecipeUsing(ItemStack ingredient) { - return SpinningRecipes.instance().findRecipeUsing(ingredient); - } + public static synchronized SpinningRecipe findRecipeFor(ItemStack result) { + return SpinningRecipes.instance().findRecipeFor(result); + } - public static synchronized SpinningRecipe findRecipeUsingFibre(ItemStack ingredient) { - return SpinningRecipes.instance().findRecipeUsingFibre(ingredient); - } + public static synchronized SpinningRecipe findRecipeUsing(ItemStack ingredient) { + return SpinningRecipes.instance().findRecipeUsing(ingredient); + } + public static synchronized SpinningRecipe findRecipeUsingFibre(ItemStack ingredient) { + return SpinningRecipes.instance().findRecipeUsingFibre(ingredient); + } } diff --git a/src/main/java/alkalus/main/core/util/AutoMap.java b/src/main/java/alkalus/main/core/util/AutoMap.java index e24a161..2c553ae 100644 --- a/src/main/java/alkalus/main/core/util/AutoMap.java +++ b/src/main/java/alkalus/main/core/util/AutoMap.java @@ -6,80 +6,79 @@ public class AutoMap implements Iterable, Cloneable, Serializable { - /** - * The Internal Map - */ - private final Map mInternalMap = new ConcurrentHashMap(); - - /** - * The Internal ID - */ - private int mInternalID = 0; - private static final long serialVersionUID = 3771412318075131790L; - - @Override - public Iterator iterator() { - return values().iterator(); - } - - public synchronized boolean setValue(V object){ - int mOriginalID = this.mInternalID; - put(object); - if (this.mInternalMap.get(mOriginalID).equals(object) || mOriginalID > this.mInternalID){ - return true; - } - else { - return false; - } - } - - public synchronized V put(V object){ - return set(object); - } - - public synchronized V set(V object){ - return mInternalMap.put(mInternalID++, object); - } - - public synchronized V get(int id){ - return mInternalMap.get(id); - } - - public synchronized Collection values(){ - return mInternalMap.values(); - } - - public synchronized int size(){ - return mInternalMap.size(); - } - - public synchronized int hashCode(){ - return mInternalMap.hashCode(); - } - - public synchronized boolean containsKey(int key){ - return mInternalMap.containsKey(key); - } - - public synchronized boolean containsValue(V value){ - return mInternalMap.containsValue(value); - } - - public synchronized boolean isEmpty(){ - return mInternalMap.isEmpty(); - } - - public synchronized boolean clear(){ - this.mInternalID = 0; - this.mInternalMap.clear(); - return true; - } - - public synchronized V[] toArray() { - Collection col = this.mInternalMap.values(); - @SuppressWarnings("unchecked") - V[] val = (V[]) col.toArray(); - return val; - } - + /** + * The Internal Map + */ + private final Map mInternalMap = new ConcurrentHashMap(); + + /** + * The Internal ID + */ + private int mInternalID = 0; + + private static final long serialVersionUID = 3771412318075131790L; + + @Override + public Iterator iterator() { + return values().iterator(); + } + + public synchronized boolean setValue(V object) { + int mOriginalID = this.mInternalID; + put(object); + if (this.mInternalMap.get(mOriginalID).equals(object) || mOriginalID > this.mInternalID) { + return true; + } else { + return false; + } + } + + public synchronized V put(V object) { + return set(object); + } + + public synchronized V set(V object) { + return mInternalMap.put(mInternalID++, object); + } + + public synchronized V get(int id) { + return mInternalMap.get(id); + } + + public synchronized Collection values() { + return mInternalMap.values(); + } + + public synchronized int size() { + return mInternalMap.size(); + } + + public synchronized int hashCode() { + return mInternalMap.hashCode(); + } + + public synchronized boolean containsKey(int key) { + return mInternalMap.containsKey(key); + } + + public synchronized boolean containsValue(V value) { + return mInternalMap.containsValue(value); + } + + public synchronized boolean isEmpty() { + return mInternalMap.isEmpty(); + } + + public synchronized boolean clear() { + this.mInternalID = 0; + this.mInternalMap.clear(); + return true; + } + + public synchronized V[] toArray() { + Collection col = this.mInternalMap.values(); + @SuppressWarnings("unchecked") + V[] val = (V[]) col.toArray(); + return val; + } } diff --git a/src/main/java/alkalus/main/core/util/BlockPos.java b/src/main/java/alkalus/main/core/util/BlockPos.java index a3a6229..f530e79 100644 --- a/src/main/java/alkalus/main/core/util/BlockPos.java +++ b/src/main/java/alkalus/main/core/util/BlockPos.java @@ -3,219 +3,216 @@ import java.io.Serializable; import java.util.HashSet; import java.util.Set; - import net.minecraft.block.Block; import net.minecraft.world.World; - import net.minecraftforge.common.DimensionManager; -public class BlockPos implements Serializable{ - - private static final long serialVersionUID = -7271947491316682006L; - public final int xPos; - public final int yPos; - public final int zPos; - public final int dim; - public final World world; - - public BlockPos(int x, int y, int z){ - this(x, y, z, 0); - } - - public BlockPos(int x, int y, int z, int dim){ - this.xPos = x; - this.yPos = y; - this.zPos = z; - this.dim = dim; - this.world = DimensionManager.getWorld(dim); - } - - public BlockPos(int x, int y, int z, World dim){ - this.xPos = x; - this.yPos = y; - this.zPos = z; - this.dim = dim.provider.dimensionId; - this.world = dim; - } - - public String getLocationString() { - return "[X: "+this.xPos+"][Y: "+this.yPos+"][Z: "+this.zPos+"][Dim: "+this.dim+"]"; - } - - @Override - public int hashCode() { - int hash = 5; - hash += (13 * this.xPos); - hash += (19 * this.yPos); - hash += (31 * this.zPos); - hash += (17 * this.dim); - return hash; - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return false; - } - if (other == this) { - return true; - } - if(!(other instanceof BlockPos)) { - return false; - } - BlockPos otherPoint = (BlockPos)other; - return this.xPos == otherPoint.xPos && this.yPos == otherPoint.yPos && this.zPos == otherPoint.zPos && this.dim == otherPoint.dim; - } - - public int distanceFrom(BlockPos target) { - if (target.dim != this.dim) { - return Short.MIN_VALUE; - } - return distanceFrom(target.xPos, target.yPos, target.zPos); - } - - /** - * - * @param x X coordinate of target. - * @param y Y coordinate of target. - * @param z Z coordinate of target. - * @return square of distance - */ - public int distanceFrom(int x, int y, int z) { - int distanceX = this.xPos - x; - int distanceY = this.yPos - y; - int distanceZ = this.zPos - z; - return distanceX * distanceX + distanceY * distanceY + distanceZ * distanceZ; - } - - public boolean isWithinRange(BlockPos target, int range) { - if (target.dim != this.dim) { - return false; - } - return isWithinRange(target.xPos, target.yPos, target.zPos, range); - } - - public boolean isWithinRange(int x, int y, int z, int range) { - return distanceFrom(x, y, z) <= (range * range); - } - - - public BlockPos getUp() { - return new BlockPos(this.xPos, this.yPos+1, this.zPos, this.dim); - } - - public BlockPos getDown() { - return new BlockPos(this.xPos, this.yPos-1, this.zPos, this.dim); - } - - public BlockPos getXPos() { - return new BlockPos(this.xPos+1, this.yPos, this.zPos, this.dim); - } - - public BlockPos getXNeg() { - return new BlockPos(this.xPos-1, this.yPos, this.zPos, this.dim); - } - - public BlockPos getZPos() { - return new BlockPos(this.xPos, this.yPos, this.zPos+1, this.dim); - } - - public BlockPos getZNeg() { - return new BlockPos(this.xPos, this.yPos, this.zPos-1, this.dim); - } - - public AutoMap getSurroundingBlocks(){ - AutoMap sides = new AutoMap(); - sides.put(getUp()); - sides.put(getDown()); - sides.put(getXPos()); - sides.put(getXNeg()); - sides.put(getZPos()); - sides.put(getZNeg()); - return sides; - } - - public Block getBlockAtPos() { - return getBlockAtPos(this); - } - - public Block getBlockAtPos(BlockPos pos) { - return getBlockAtPos(world, pos); - } - - public Block getBlockAtPos(World world, BlockPos pos) { - return world.getBlock(pos.xPos, pos.yPos, pos.zPos); - } - - public int getMetaAtPos() { - return getMetaAtPos(this); - } - - public int getMetaAtPos(BlockPos pos) { - return getMetaAtPos(world, pos); - } - - public int getMetaAtPos(World world, BlockPos pos) { - return world.getBlockMetadata(pos.xPos, pos.yPos, pos.zPos); - } - - public boolean hasSimilarNeighbour() { - return hasSimilarNeighbour(false); - } - - /** - * @param strict - Does this check Meta Data? - * @return - Does this block have a neighbour that is the same? - */ - public boolean hasSimilarNeighbour(boolean strict) { - for (BlockPos g : getSurroundingBlocks().values()) { - if (getBlockAtPos(g) == getBlockAtPos()) { - if (!strict) { - return true; - } - else { - if (getMetaAtPos() == getMetaAtPos(g)) { - return true; - } - } - } - } - return false; - } - - public AutoMap getSimilarNeighbour() { - return getSimilarNeighbour(false); - } - - /** - * @param strict - Does this check Meta Data? - * @return - Does this block have a neighbour that is the same? - */ - public AutoMap getSimilarNeighbour(boolean strict) { - AutoMap sides = new AutoMap(); - for (BlockPos g : getSurroundingBlocks().values()) { - if (getBlockAtPos(g) == getBlockAtPos()) { - if (!strict) { - sides.put(g); - } - else { - if (getMetaAtPos() == getMetaAtPos(g)) { - sides.put(g); - } - } - } - } - return sides; - } - - public Set getValidNeighboursAndSelf(){ - AutoMap h = getSimilarNeighbour(true); - h.put(this); - Set result = new HashSet(); - for (BlockPos f : h.values()) { - result.add(f); - } - return result; - } - +public class BlockPos implements Serializable { + + private static final long serialVersionUID = -7271947491316682006L; + public final int xPos; + public final int yPos; + public final int zPos; + public final int dim; + public final World world; + + public BlockPos(int x, int y, int z) { + this(x, y, z, 0); + } + + public BlockPos(int x, int y, int z, int dim) { + this.xPos = x; + this.yPos = y; + this.zPos = z; + this.dim = dim; + this.world = DimensionManager.getWorld(dim); + } + + public BlockPos(int x, int y, int z, World dim) { + this.xPos = x; + this.yPos = y; + this.zPos = z; + this.dim = dim.provider.dimensionId; + this.world = dim; + } + + public String getLocationString() { + return "[X: " + this.xPos + "][Y: " + this.yPos + "][Z: " + this.zPos + "][Dim: " + this.dim + "]"; + } + + @Override + public int hashCode() { + int hash = 5; + hash += (13 * this.xPos); + hash += (19 * this.yPos); + hash += (31 * this.zPos); + hash += (17 * this.dim); + return hash; + } + + @Override + public boolean equals(Object other) { + if (other == null) { + return false; + } + if (other == this) { + return true; + } + if (!(other instanceof BlockPos)) { + return false; + } + BlockPos otherPoint = (BlockPos) other; + return this.xPos == otherPoint.xPos + && this.yPos == otherPoint.yPos + && this.zPos == otherPoint.zPos + && this.dim == otherPoint.dim; + } + + public int distanceFrom(BlockPos target) { + if (target.dim != this.dim) { + return Short.MIN_VALUE; + } + return distanceFrom(target.xPos, target.yPos, target.zPos); + } + + /** + * + * @param x X coordinate of target. + * @param y Y coordinate of target. + * @param z Z coordinate of target. + * @return square of distance + */ + public int distanceFrom(int x, int y, int z) { + int distanceX = this.xPos - x; + int distanceY = this.yPos - y; + int distanceZ = this.zPos - z; + return distanceX * distanceX + distanceY * distanceY + distanceZ * distanceZ; + } + + public boolean isWithinRange(BlockPos target, int range) { + if (target.dim != this.dim) { + return false; + } + return isWithinRange(target.xPos, target.yPos, target.zPos, range); + } + + public boolean isWithinRange(int x, int y, int z, int range) { + return distanceFrom(x, y, z) <= (range * range); + } + + public BlockPos getUp() { + return new BlockPos(this.xPos, this.yPos + 1, this.zPos, this.dim); + } + + public BlockPos getDown() { + return new BlockPos(this.xPos, this.yPos - 1, this.zPos, this.dim); + } + + public BlockPos getXPos() { + return new BlockPos(this.xPos + 1, this.yPos, this.zPos, this.dim); + } + + public BlockPos getXNeg() { + return new BlockPos(this.xPos - 1, this.yPos, this.zPos, this.dim); + } + + public BlockPos getZPos() { + return new BlockPos(this.xPos, this.yPos, this.zPos + 1, this.dim); + } + + public BlockPos getZNeg() { + return new BlockPos(this.xPos, this.yPos, this.zPos - 1, this.dim); + } + + public AutoMap getSurroundingBlocks() { + AutoMap sides = new AutoMap(); + sides.put(getUp()); + sides.put(getDown()); + sides.put(getXPos()); + sides.put(getXNeg()); + sides.put(getZPos()); + sides.put(getZNeg()); + return sides; + } + + public Block getBlockAtPos() { + return getBlockAtPos(this); + } + + public Block getBlockAtPos(BlockPos pos) { + return getBlockAtPos(world, pos); + } + + public Block getBlockAtPos(World world, BlockPos pos) { + return world.getBlock(pos.xPos, pos.yPos, pos.zPos); + } + + public int getMetaAtPos() { + return getMetaAtPos(this); + } + + public int getMetaAtPos(BlockPos pos) { + return getMetaAtPos(world, pos); + } + + public int getMetaAtPos(World world, BlockPos pos) { + return world.getBlockMetadata(pos.xPos, pos.yPos, pos.zPos); + } + + public boolean hasSimilarNeighbour() { + return hasSimilarNeighbour(false); + } + + /** + * @param strict - Does this check Meta Data? + * @return - Does this block have a neighbour that is the same? + */ + public boolean hasSimilarNeighbour(boolean strict) { + for (BlockPos g : getSurroundingBlocks().values()) { + if (getBlockAtPos(g) == getBlockAtPos()) { + if (!strict) { + return true; + } else { + if (getMetaAtPos() == getMetaAtPos(g)) { + return true; + } + } + } + } + return false; + } + + public AutoMap getSimilarNeighbour() { + return getSimilarNeighbour(false); + } + + /** + * @param strict - Does this check Meta Data? + * @return - Does this block have a neighbour that is the same? + */ + public AutoMap getSimilarNeighbour(boolean strict) { + AutoMap sides = new AutoMap(); + for (BlockPos g : getSurroundingBlocks().values()) { + if (getBlockAtPos(g) == getBlockAtPos()) { + if (!strict) { + sides.put(g); + } else { + if (getMetaAtPos() == getMetaAtPos(g)) { + sides.put(g); + } + } + } + } + return sides; + } + + public Set getValidNeighboursAndSelf() { + AutoMap h = getSimilarNeighbour(true); + h.put(this); + Set result = new HashSet(); + for (BlockPos f : h.values()) { + result.add(f); + } + return result; + } } diff --git a/src/main/java/alkalus/main/core/util/Logger.java b/src/main/java/alkalus/main/core/util/Logger.java index 257c450..2c0d322 100644 --- a/src/main/java/alkalus/main/core/util/Logger.java +++ b/src/main/java/alkalus/main/core/util/Logger.java @@ -1,41 +1,38 @@ package alkalus.main.core.util; -import org.apache.logging.log4j.LogManager; - import alkalus.main.core.WitcheryExtras; +import org.apache.logging.log4j.LogManager; public class Logger { - public static final org.apache.logging.log4j.Logger modLogger = Logger.makeLogger(); - - public static org.apache.logging.log4j.Logger makeLogger() { - final org.apache.logging.log4j.Logger loggers = LogManager.getLogger(WitcheryExtras.NAME); - return loggers; - } + public static final org.apache.logging.log4j.Logger modLogger = Logger.makeLogger(); - public static final org.apache.logging.log4j.Logger getLogger(){ - return modLogger; - } + public static org.apache.logging.log4j.Logger makeLogger() { + final org.apache.logging.log4j.Logger loggers = LogManager.getLogger(WitcheryExtras.NAME); + return loggers; + } - public void INFO(final String s) { - modLogger.info(s); - } + public static final org.apache.logging.log4j.Logger getLogger() { + return modLogger; + } - public void WARNING(final String s) { - modLogger.warn(s); - } + public void INFO(final String s) { + modLogger.info(s); + } - public void ERROR(final String s) { - modLogger.fatal(s); + public void WARNING(final String s) { + modLogger.warn(s); + } - } + public void ERROR(final String s) { + modLogger.fatal(s); + } - public static void REFLECTION(String string) { - modLogger.info("[Reflection] "+string); - } - - public static void ASM(String string) { - modLogger.info("[ASM] "+string); - } + public static void REFLECTION(String string) { + modLogger.info("[Reflection] " + string); + } + public static void ASM(String string) { + modLogger.info("[ASM] " + string); + } } diff --git a/src/main/java/alkalus/main/core/util/MathUtils.java b/src/main/java/alkalus/main/core/util/MathUtils.java index 2f3359c..d4cec8f 100644 --- a/src/main/java/alkalus/main/core/util/MathUtils.java +++ b/src/main/java/alkalus/main/core/util/MathUtils.java @@ -4,317 +4,299 @@ public class MathUtils { - /** - * Returns a psuedo-random number between min and max, inclusive. - * The difference between min and max can be at most - * Integer.MAX_VALUE - 1. - * - * @param min Minimim value - * @param max Maximim value. Must be greater than min. - * @return Integer between min and max, inclusive. - * @see java.util.Random#nextInt(int) - */ - - final static Random rand = new Random(); - - public static int randInt(final int min, final int max) { - // nextInt is normally exclusive of the top value, - // so add 1 to make it inclusive - return rand.nextInt((max - min) + 1) + min; - } - - public static double getChanceOfXOverYRuns(final double x, final double y){ - return (1-Math.pow((1-x), y)); - } - - - /** - * Returns a psuedo-random number between min and max, inclusive. - * The difference between min and max can be at most - * Long.MAX_VALUE - 1. - * - * @param min Minimim value - * @param max Maximim value. Must be greater than min. - * @return Long between min and max, inclusive. - * @see java.util.Random#nextLong(long) - */ - public static long randLong(final long min, final long max) { - // nextInt is normally exclusive of the top value, - // so add 1 to make it inclusive - return MathUtils.nextLong(rand,(max - min) + 1) + min; - } - private static long nextLong(final Random rng, final long n) { - // error checking and 2^x checking removed for simplicity. - long bits, val; - do { - bits = (rng.nextLong() << 1) >>> 1; - val = bits % n; - } while (((bits-val)+(n-1)) < 0L); - return val; - } - - - /** - * Returns a psuedo-random number between min and max, inclusive. - * The difference between min and max can be at most - * Double.MAX_VALUE - 1. - * - * @param min Minimim value - * @param max Maximim value. Must be greater than min. - * @return Double between min and max, inclusive. - * @see java.util.Random#nextDouble(double) - */ - public static double randDouble(final double min, final double max) { - // nextInt is normally exclusive of the top value, - // so add 1 to make it inclusive - return MathUtils.nextDouble(rand,(max - min) + 1) + min; - } - - private static double nextDouble(final Random rng, final double n) { - // error checking and 2^x checking removed for simplicity. - double bits, val; - do { - bits = (rng.nextLong() << 1) >>> 1; - val = bits % n; - } while (((bits-val)+(n-1)) < 0L); - return val; - } - - /** - * Returns a psuedo-random number between min and max, inclusive. - * The difference between min and max can be at most - * Float.MAX_VALUE - 1. - * - * @param min Minimim value - * @param max Maximim value. Must be greater than min. - * @return Float between min and max, inclusive. - * @see java.util.Random#nextFloat(float) - */ - public static float randFloat(final float min, final float max) { - // nextInt is normally exclusive of the top value, - // so add 1 to make it inclusive - return MathUtils.nextFloat(rand,(max - min) + 1) + min; - } - - private static float nextFloat(final Random rng, final float n) { - // error checking and 2^x checking removed for simplicity. - float bits, val; - do { - bits = (rng.nextLong() << 1) >>> 1; - val = bits % n; - } while (((bits-val)+(n-1)) < 0L); - return val; - } - - - /** - * Returns a percentage. - * The returned number is the % of X in Y. - * Supports Doubles. - * - * @param current Current value. - * @param max Maximim value. Must be greater than min. - * @return double between min and max, inclusive. - */ - public static double findPercentage(final double current, final double max){ - return Math.round(((current / max) * 100) * 100.00) / 100.00; - } - - public static int findPercentageOfInt(long input, float percentage){ - return (int)(input*(percentage/100.0f)); - } - - - //Smooth Rounding Function - /** - * Returns a double. - * The returned number is d rounded to the nearest d.01. - * Supports Doubles. - * - * @param current Current value. - * @return double Rounded value. - */ - public static double decimalRounding(final double d) { - return Math.round(d * 2) / 2.0; - } - - - //Smooth Rounding Function (Nearest 5) - /** - * Returns a double. - * The returned number is d rounded to the nearest d.5. - * Supports Doubles. - * - * @param current Current value. - * @return double Rounded value. - */ - public static double decimalRoundingToWholes(final double d) { - return 5*(Math.round(d/5)); - } - - //Smooth Rounding Function - /** - * Returns a integer. - * The returned number is d rounded to the nearest flat integer. - * Supports Doubles as input. - * - * @param current Current value. - * @return integer Rounded value. - */ - public static int roundToClosestInt(final double d) { - return (int) (Math.round(d * 2) / 2.0); - } - - public static int roundToClosestMultiple(final double number, final int multiple) { - int result = multiple; - if ((number % multiple) == 0) { - return (int) number; - } - // If not already multiple of given number - if ((number % multiple) != 0) { - final int division = (int) ((number / multiple) + 1); - result = division * multiple; - } - return result; - } - - - //Smooth Rounding Function - /** - * Returns a long. - * The returned number is d rounded to the nearest flat long. - * Supports Doubles as input. - * - * @param current Current value. - * @return long Rounded value. - */ - public static long roundToClosestLong(final double d) { - return (long) (Math.round(d * 2) / 2.0); - } - - - /** - * Returns a boolean. - * The returned boolean is wether or not X evenly fits in to Y. - * Supports ints. - * - * @param x Value A. - * @param y Value B. Must be greater than min. - * @return boolean Whether or not it divides evenly. - */ - public static boolean divideXintoY(final int x, final int y){ - if ((x % y) == 0) - { - return true; - } - return false; - } - - - /** - * Returns a boolean. - * The returned boolean is based on the odd/eveness of the input. - * Supports ints. - * - * @param x Value A. - * @return boolean Whether or not it divides evenly. - */ - public static boolean isNumberEven(final int x){ - if ((x % 2) == 0) - { - return true; - } - return false; - } - - - - /** - * Returns an int. - * The returned number is the value on i + 273.15F. - * Supports ints. - * - * @param i Temp in Celcius. - * @return int The celcius temp returned as Kelvin, rounded to the readest whole. - */ - public static float celsiusToKelvin(final int i){ - final double f = i + 273.15F; - return (int)decimalRoundingToWholes(f); - } - - - /** - * Returns a hexInteger. - * The returned number is the hex value of the input. - * Supports ints. - * - * @param input Current value. - * @return hexInteger. - */ - public static int getHexNumberFromInt(final int input){ - final String result = Integer.toHexString(input); - final int resultINT = Integer.getInteger(result); - return resultINT; - } - - - /** - * Returns a hexInteger. - * The returned value is between min and max. - * Supports ints. - * - * @param min Minimum value. - * @param max Maximium value. Must be greater than min. - * @return hexInteger between min and max, inclusive. - */ - public static int generateRandomHexValue(final int min, final int max){ - return getHexNumberFromInt(randInt(min, max)); - } - - public static long[] simplifyNumbersToSmallestForm(final long[] inputArray){ - final long GCD = gcd(inputArray); - final long[] outputArray = new long[inputArray.length]; - for (int i=0;i 0) { - return outputArray; - } - return new long[] {}; - } - - private static long gcd(long a, long b){ - while (b > 0) - { - final long temp = b; - b = a % b; // % is remainder - a = temp; - } - return a; - } - - private static long gcd(final long[] input){ - long result = input[0]; - for(int i = 1; i < input.length; i++) { - result = gcd(result, input[i]); - } - return result; - } - - public final static int returnLargestNumber(final int a, final int b){ - if (a > b){ - return a; - } - else if (a == b){ - return a; - } - else { - return b; - } - } - + /** + * Returns a psuedo-random number between min and max, inclusive. + * The difference between min and max can be at most + * Integer.MAX_VALUE - 1. + * + * @param min Minimim value + * @param max Maximim value. Must be greater than min. + * @return Integer between min and max, inclusive. + * @see java.util.Random#nextInt(int) + */ + static final Random rand = new Random(); + + public static int randInt(final int min, final int max) { + // nextInt is normally exclusive of the top value, + // so add 1 to make it inclusive + return rand.nextInt((max - min) + 1) + min; + } + + public static double getChanceOfXOverYRuns(final double x, final double y) { + return (1 - Math.pow((1 - x), y)); + } + + /** + * Returns a psuedo-random number between min and max, inclusive. + * The difference between min and max can be at most + * Long.MAX_VALUE - 1. + * + * @param min Minimim value + * @param max Maximim value. Must be greater than min. + * @return Long between min and max, inclusive. + * @see java.util.Random#nextLong(long) + */ + public static long randLong(final long min, final long max) { + // nextInt is normally exclusive of the top value, + // so add 1 to make it inclusive + return MathUtils.nextLong(rand, (max - min) + 1) + min; + } + + private static long nextLong(final Random rng, final long n) { + // error checking and 2^x checking removed for simplicity. + long bits, val; + do { + bits = (rng.nextLong() << 1) >>> 1; + val = bits % n; + } while (((bits - val) + (n - 1)) < 0L); + return val; + } + + /** + * Returns a psuedo-random number between min and max, inclusive. + * The difference between min and max can be at most + * Double.MAX_VALUE - 1. + * + * @param min Minimim value + * @param max Maximim value. Must be greater than min. + * @return Double between min and max, inclusive. + * @see java.util.Random#nextDouble(double) + */ + public static double randDouble(final double min, final double max) { + // nextInt is normally exclusive of the top value, + // so add 1 to make it inclusive + return MathUtils.nextDouble(rand, (max - min) + 1) + min; + } + + private static double nextDouble(final Random rng, final double n) { + // error checking and 2^x checking removed for simplicity. + double bits, val; + do { + bits = (rng.nextLong() << 1) >>> 1; + val = bits % n; + } while (((bits - val) + (n - 1)) < 0L); + return val; + } + + /** + * Returns a psuedo-random number between min and max, inclusive. + * The difference between min and max can be at most + * Float.MAX_VALUE - 1. + * + * @param min Minimim value + * @param max Maximim value. Must be greater than min. + * @return Float between min and max, inclusive. + * @see java.util.Random#nextFloat(float) + */ + public static float randFloat(final float min, final float max) { + // nextInt is normally exclusive of the top value, + // so add 1 to make it inclusive + return MathUtils.nextFloat(rand, (max - min) + 1) + min; + } + + private static float nextFloat(final Random rng, final float n) { + // error checking and 2^x checking removed for simplicity. + float bits, val; + do { + bits = (rng.nextLong() << 1) >>> 1; + val = bits % n; + } while (((bits - val) + (n - 1)) < 0L); + return val; + } + + /** + * Returns a percentage. + * The returned number is the % of X in Y. + * Supports Doubles. + * + * @param current Current value. + * @param max Maximim value. Must be greater than min. + * @return double between min and max, inclusive. + */ + public static double findPercentage(final double current, final double max) { + return Math.round(((current / max) * 100) * 100.00) / 100.00; + } + + public static int findPercentageOfInt(long input, float percentage) { + return (int) (input * (percentage / 100.0f)); + } + + // Smooth Rounding Function + /** + * Returns a double. + * The returned number is d rounded to the nearest d.01. + * Supports Doubles. + * + * @param current Current value. + * @return double Rounded value. + */ + public static double decimalRounding(final double d) { + return Math.round(d * 2) / 2.0; + } + + // Smooth Rounding Function (Nearest 5) + /** + * Returns a double. + * The returned number is d rounded to the nearest d.5. + * Supports Doubles. + * + * @param current Current value. + * @return double Rounded value. + */ + public static double decimalRoundingToWholes(final double d) { + return 5 * (Math.round(d / 5)); + } + + // Smooth Rounding Function + /** + * Returns a integer. + * The returned number is d rounded to the nearest flat integer. + * Supports Doubles as input. + * + * @param current Current value. + * @return integer Rounded value. + */ + public static int roundToClosestInt(final double d) { + return (int) (Math.round(d * 2) / 2.0); + } + + public static int roundToClosestMultiple(final double number, final int multiple) { + int result = multiple; + if ((number % multiple) == 0) { + return (int) number; + } + // If not already multiple of given number + if ((number % multiple) != 0) { + final int division = (int) ((number / multiple) + 1); + result = division * multiple; + } + return result; + } + + // Smooth Rounding Function + /** + * Returns a long. + * The returned number is d rounded to the nearest flat long. + * Supports Doubles as input. + * + * @param current Current value. + * @return long Rounded value. + */ + public static long roundToClosestLong(final double d) { + return (long) (Math.round(d * 2) / 2.0); + } + + /** + * Returns a boolean. + * The returned boolean is wether or not X evenly fits in to Y. + * Supports ints. + * + * @param x Value A. + * @param y Value B. Must be greater than min. + * @return boolean Whether or not it divides evenly. + */ + public static boolean divideXintoY(final int x, final int y) { + if ((x % y) == 0) { + return true; + } + return false; + } + + /** + * Returns a boolean. + * The returned boolean is based on the odd/eveness of the input. + * Supports ints. + * + * @param x Value A. + * @return boolean Whether or not it divides evenly. + */ + public static boolean isNumberEven(final int x) { + if ((x % 2) == 0) { + return true; + } + return false; + } + + /** + * Returns an int. + * The returned number is the value on i + 273.15F. + * Supports ints. + * + * @param i Temp in Celcius. + * @return int The celcius temp returned as Kelvin, rounded to the readest whole. + */ + public static float celsiusToKelvin(final int i) { + final double f = i + 273.15F; + return (int) decimalRoundingToWholes(f); + } + + /** + * Returns a hexInteger. + * The returned number is the hex value of the input. + * Supports ints. + * + * @param input Current value. + * @return hexInteger. + */ + public static int getHexNumberFromInt(final int input) { + final String result = Integer.toHexString(input); + final int resultINT = Integer.getInteger(result); + return resultINT; + } + + /** + * Returns a hexInteger. + * The returned value is between min and max. + * Supports ints. + * + * @param min Minimum value. + * @param max Maximium value. Must be greater than min. + * @return hexInteger between min and max, inclusive. + */ + public static int generateRandomHexValue(final int min, final int max) { + return getHexNumberFromInt(randInt(min, max)); + } + + public static long[] simplifyNumbersToSmallestForm(final long[] inputArray) { + final long GCD = gcd(inputArray); + final long[] outputArray = new long[inputArray.length]; + for (int i = 0; i < inputArray.length; i++) { + if (GCD != 0) { + outputArray[i] = (inputArray[i] / GCD); + } else { + outputArray[i] = inputArray[i]; + } + } + if (outputArray.length > 0) { + return outputArray; + } + return new long[] {}; + } + + private static long gcd(long a, long b) { + while (b > 0) { + final long temp = b; + b = a % b; // % is remainder + a = temp; + } + return a; + } + + private static long gcd(final long[] input) { + long result = input[0]; + for (int i = 1; i < input.length; i++) { + result = gcd(result, input[i]); + } + return result; + } + + public static final int returnLargestNumber(final int a, final int b) { + if (a > b) { + return a; + } else if (a == b) { + return a; + } else { + return b; + } + } } diff --git a/src/main/java/alkalus/main/core/util/NBTUtils.java b/src/main/java/alkalus/main/core/util/NBTUtils.java index 621a6af..253d20c 100644 --- a/src/main/java/alkalus/main/core/util/NBTUtils.java +++ b/src/main/java/alkalus/main/core/util/NBTUtils.java @@ -1,451 +1,447 @@ package alkalus.main.core.util; +import alkalus.main.core.WitcheryExtras; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Map; - import net.minecraft.item.ItemStack; import net.minecraft.nbt.*; -import alkalus.main.core.WitcheryExtras; - public class NBTUtils { - public static NBTTagCompound getNBT(ItemStack aStack) { - NBTTagCompound rNBT = aStack.getTagCompound(); - return ((rNBT == null) ? new NBTTagCompound() : rNBT); - } - - public static void setBookTitle(ItemStack aStack, String aTitle) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString("title", aTitle); - setNBT(aStack, tNBT); - } - - public static String getBookTitle(ItemStack aStack) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString("title"); - } - - public static ItemStack[] readItemsFromNBT(ItemStack itemstack) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = tNBT.getTagList("Items", 10); - ItemStack inventory[] = new ItemStack[list.tagCount()]; - for (int i = 0; i < list.tagCount(); i++) { - final NBTTagCompound data = list.getCompoundTagAt(i); - final int slot = data.getInteger("Slot"); - if ((slot >= 0) && (slot < list.tagCount())) { - if (ItemStack.loadItemStackFromNBT(data) == null) { - inventory[slot] = null; - } else { - inventory[slot] = ItemStack.loadItemStackFromNBT(data); - } - - } - } - return inventory; - } - - public static ItemStack[] readItemsFromNBT(ItemStack itemstack, String customkey) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = tNBT.getTagList(customkey, 10); - ItemStack inventory[] = new ItemStack[list.tagCount()]; - for (int i = 0; i < list.tagCount(); i++) { - final NBTTagCompound data = list.getCompoundTagAt(i); - final int slot = data.getInteger("Slot"); - if ((slot >= 0) && (slot < list.tagCount())) { - if (ItemStack.loadItemStackFromNBT(data) == null) { - inventory[slot] = null; - } else { - inventory[slot] = ItemStack.loadItemStackFromNBT(data); - } - - } - } - return inventory; - } - - public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = new NBTTagList(); - for (int i = 0; i < stored.length; i++) { - final ItemStack stack = stored[i]; - if (stack != null) { - final NBTTagCompound data = new NBTTagCompound(); - stack.writeToNBT(data); - data.setInteger("Slot", i); - list.appendTag(data); - } - } - tNBT.setTag("Items", list); - itemstack.setTagCompound(tNBT); - return itemstack; - } - - public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored, String customkey) { - NBTTagCompound tNBT = getNBT(itemstack); - final NBTTagList list = new NBTTagList(); - for (int i = 0; i < stored.length; i++) { - final ItemStack stack = stored[i]; - if (stack != null) { - final NBTTagCompound data = new NBTTagCompound(); - stack.writeToNBT(data); - data.setInteger("Slot", i); - list.appendTag(data); - } - } - tNBT.setTag(customkey, list); - itemstack.setTagCompound(tNBT); - return itemstack; - } - - - public static void setBoolean(ItemStack aStack, String aTag, boolean aBoolean) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setBoolean(aTag, aBoolean); - setNBT(aStack, tNBT); - } - - public static boolean getBoolean(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getBoolean(aTag); - } - - public static void setInteger(ItemStack aStack, String aTag, int aInt) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setInteger(aTag, aInt); - setNBT(aStack, tNBT); - } - - public static int getInteger(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getInteger(aTag); - } - - public static void setLong(ItemStack aStack, String aTag, long aInt) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setLong(aTag, aInt); - setNBT(aStack, tNBT); - } - - public static long getLong(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getLong(aTag); - } - - public static void setFloat(ItemStack aStack, String aTag, float aInt) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setFloat(aTag, aInt); - setNBT(aStack, tNBT); - } - - public static float getFloat(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getFloat(aTag); - } - - public static void setString(ItemStack aStack, String aTag, String aString) { - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString(aTag, aString); - setNBT(aStack, tNBT); - } - - public static String getString(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString(aTag); - } - - public static boolean doesStringExist(ItemStack aStack, String aTag) { - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.hasKey(aTag); - } - - public static boolean tryIterateNBTData(ItemStack aStack) { - try { - NBTTagCompound aNBT = NBTUtils.getNBT(aStack); - if (aNBT != null) { - if (!aNBT.hasNoTags()) { - Map mInternalMap = getField(aNBT, "tagMap"); - if (mInternalMap != null) { - for (Map.Entry e : mInternalMap.entrySet()) { - WitcheryExtras.log(0, "Key: " + e.getKey().toString() + " | Value: " + e.getValue() + " | Type: "+e.getValue().getClass().getName()); - } - return true; - } else { - WitcheryExtras.log(0, "Data map reflected from NBTTagCompound was not valid."); - return false; - } - } - } - } catch (Throwable t) {} - return false; - } - - // Botania soulbind handling - public static boolean setBotanicaSoulboundOwner(ItemStack aStack, String aName) { - final String TAG_SOULBIND = "soulbind"; - NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString(TAG_SOULBIND, aName); - setNBT(aStack, tNBT); - if (NBTUtils.doesStringExist(aStack, TAG_SOULBIND)) { - return true; - } else { - return false; - } - } - - public static String getBotanicaSoulboundOwner(ItemStack aStack) { - final String TAG_SOULBIND = "soulbind"; - NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString(TAG_SOULBIND); - } - - public static boolean hasKey(ItemStack stack, String key) { - final NBTTagCompound itemData = getNBT(stack); - if (itemData.hasKey(key)) { - return true; - } - return false; - } - - public static boolean createIntegerTagCompound(ItemStack rStack, String tagName, String keyName, int keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setInteger(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createLongTagCompound(ItemStack rStack, String tagName, String keyName, long keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setLong(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createStringTagCompound(ItemStack rStack, String tagName, String keyName, String keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setString(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createFloatTagCompound(ItemStack rStack, String tagName, String keyName, float keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setFloat(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createByteTagCompound(ItemStack rStack, String tagName, String keyName, byte keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setByte(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createBooleanTagCompound(ItemStack rStack, String tagName, String keyName, boolean keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - final NBTTagCompound tagNBT = new NBTTagCompound(); - tagNBT.setBoolean(keyName, keyValue); - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static boolean createTagCompound(ItemStack rStack, String tagName, NBTTagCompound keyValue) { - final NBTTagCompound tagMain = getNBT(rStack); - NBTTagCompound tagNBT = keyValue; - tagMain.setTag(tagName, tagNBT); - rStack.setTagCompound(tagMain); - return true; - } - - public static int getIntegerTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getInteger(keyName); - } - } - return 0; - } - - public static long getLongTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getLong(keyName); - } - } - return 0L; - } - - public static String getStringTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getString(keyName); - } - } - return null; - } - - public static float getFloatTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getFloat(keyName); - } - } - return 0; - } - - public static double getByteTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getByte(keyName); - } - } - return 0; - } - - public static boolean getBooleanTagCompound(ItemStack aStack, String tagName, String keyName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT.getBoolean(keyName); - } - } - return false; - } - - public static NBTTagCompound getTagCompound(ItemStack aStack, String tagName) { - NBTTagCompound aNBT = getNBT(aStack); - if (aNBT != null && hasKey(aStack, tagName)) { - aNBT = aNBT.getCompoundTag(tagName); - if (aNBT != null) { - return aNBT; - } - } - return null; - } - - public static boolean hasKeyInTagCompound(ItemStack stack, String tag, String key) { - NBTTagCompound aNBT = stack.getTagCompound(); - if (aNBT != null) { - aNBT = aNBT.getCompoundTag(tag); - if (aNBT.hasKey(key)) { - return true; - } - } - return false; - } - - public static void setNBT(final ItemStack aStack, final NBTTagCompound aNBT) { - if (aNBT == null) { - aStack.setTagCompound((NBTTagCompound) null); - return; - } - final ArrayList tTagsToRemove = new ArrayList(); - for (final Object tKey : aNBT.func_150296_c()) { - final NBTBase tValue = aNBT.getTag((String) tKey); - if (tValue == null - || (tValue instanceof NBTBase.NBTPrimitive - && ((NBTBase.NBTPrimitive) tValue).func_150291_c() == 0L) - || (tValue instanceof NBTTagString - && isStringInvalid(((NBTTagString) tValue).func_150285_a_()))) { - tTagsToRemove.add((String) tKey); - } - } - for (final Object tKey : tTagsToRemove) { - aNBT.removeTag((String) tKey); - } - aStack.setTagCompound(aNBT.hasNoTags() ? null : aNBT); - } - - public static boolean isStringInvalid(final Object aString) { - return aString == null || aString.toString().isEmpty(); - } - - public static void setPunchCardData(final ItemStack aStack, final String aPunchCardData) { - final NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString("GT.PunchCardData", aPunchCardData); - setNBT(aStack, tNBT); - } - - public static String getPunchCardData(final ItemStack aStack) { - final NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString("GT.PunchCardData"); - } - - public static void setLighterFuel(final ItemStack aStack, final long aFuel) { - final NBTTagCompound tNBT = getNBT(aStack); - tNBT.setLong("GT.LighterFuel", aFuel); - setNBT(aStack, tNBT); - } - - public static long getLighterFuel(final ItemStack aStack) { - final NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getLong("GT.LighterFuel"); - } - - public static void setMapID(final ItemStack aStack, final short aMapID) { - final NBTTagCompound tNBT = getNBT(aStack); - tNBT.setShort("map_id", aMapID); - setNBT(aStack, tNBT); - } - - public static short getMapID(final ItemStack aStack) { - final NBTTagCompound tNBT = getNBT(aStack); - if (!tNBT.hasKey("map_id")) { - return -1; - } - return tNBT.getShort("map_id"); - } - - public static void setBookAuthor(final ItemStack aStack, final String aAuthor) { - final NBTTagCompound tNBT = getNBT(aStack); - tNBT.setString("author", aAuthor); - setNBT(aStack, tNBT); - } - - public static String getBookAuthor(final ItemStack aStack) { - final NBTTagCompound tNBT = getNBT(aStack); - return tNBT.getString("author"); - } - - @SuppressWarnings("unchecked") - public static V getField(final Object object, final String fieldName) { - Class clazz = object.getClass(); - while (clazz != null) { - try { - final Field field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - return (V) field.get(object); - } catch (final NoSuchFieldException e) { - clazz = clazz.getSuperclass(); - } catch (final Exception e) { - throw new IllegalStateException(e); - } - } - return null; - } - + public static NBTTagCompound getNBT(ItemStack aStack) { + NBTTagCompound rNBT = aStack.getTagCompound(); + return ((rNBT == null) ? new NBTTagCompound() : rNBT); + } + + public static void setBookTitle(ItemStack aStack, String aTitle) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString("title", aTitle); + setNBT(aStack, tNBT); + } + + public static String getBookTitle(ItemStack aStack) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString("title"); + } + + public static ItemStack[] readItemsFromNBT(ItemStack itemstack) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = tNBT.getTagList("Items", 10); + ItemStack inventory[] = new ItemStack[list.tagCount()]; + for (int i = 0; i < list.tagCount(); i++) { + final NBTTagCompound data = list.getCompoundTagAt(i); + final int slot = data.getInteger("Slot"); + if ((slot >= 0) && (slot < list.tagCount())) { + if (ItemStack.loadItemStackFromNBT(data) == null) { + inventory[slot] = null; + } else { + inventory[slot] = ItemStack.loadItemStackFromNBT(data); + } + } + } + return inventory; + } + + public static ItemStack[] readItemsFromNBT(ItemStack itemstack, String customkey) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = tNBT.getTagList(customkey, 10); + ItemStack inventory[] = new ItemStack[list.tagCount()]; + for (int i = 0; i < list.tagCount(); i++) { + final NBTTagCompound data = list.getCompoundTagAt(i); + final int slot = data.getInteger("Slot"); + if ((slot >= 0) && (slot < list.tagCount())) { + if (ItemStack.loadItemStackFromNBT(data) == null) { + inventory[slot] = null; + } else { + inventory[slot] = ItemStack.loadItemStackFromNBT(data); + } + } + } + return inventory; + } + + public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = new NBTTagList(); + for (int i = 0; i < stored.length; i++) { + final ItemStack stack = stored[i]; + if (stack != null) { + final NBTTagCompound data = new NBTTagCompound(); + stack.writeToNBT(data); + data.setInteger("Slot", i); + list.appendTag(data); + } + } + tNBT.setTag("Items", list); + itemstack.setTagCompound(tNBT); + return itemstack; + } + + public static ItemStack writeItemsToNBT(ItemStack itemstack, ItemStack[] stored, String customkey) { + NBTTagCompound tNBT = getNBT(itemstack); + final NBTTagList list = new NBTTagList(); + for (int i = 0; i < stored.length; i++) { + final ItemStack stack = stored[i]; + if (stack != null) { + final NBTTagCompound data = new NBTTagCompound(); + stack.writeToNBT(data); + data.setInteger("Slot", i); + list.appendTag(data); + } + } + tNBT.setTag(customkey, list); + itemstack.setTagCompound(tNBT); + return itemstack; + } + + public static void setBoolean(ItemStack aStack, String aTag, boolean aBoolean) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setBoolean(aTag, aBoolean); + setNBT(aStack, tNBT); + } + + public static boolean getBoolean(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getBoolean(aTag); + } + + public static void setInteger(ItemStack aStack, String aTag, int aInt) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setInteger(aTag, aInt); + setNBT(aStack, tNBT); + } + + public static int getInteger(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getInteger(aTag); + } + + public static void setLong(ItemStack aStack, String aTag, long aInt) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setLong(aTag, aInt); + setNBT(aStack, tNBT); + } + + public static long getLong(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getLong(aTag); + } + + public static void setFloat(ItemStack aStack, String aTag, float aInt) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setFloat(aTag, aInt); + setNBT(aStack, tNBT); + } + + public static float getFloat(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getFloat(aTag); + } + + public static void setString(ItemStack aStack, String aTag, String aString) { + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString(aTag, aString); + setNBT(aStack, tNBT); + } + + public static String getString(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString(aTag); + } + + public static boolean doesStringExist(ItemStack aStack, String aTag) { + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.hasKey(aTag); + } + + public static boolean tryIterateNBTData(ItemStack aStack) { + try { + NBTTagCompound aNBT = NBTUtils.getNBT(aStack); + if (aNBT != null) { + if (!aNBT.hasNoTags()) { + Map mInternalMap = getField(aNBT, "tagMap"); + if (mInternalMap != null) { + for (Map.Entry e : mInternalMap.entrySet()) { + WitcheryExtras.log( + 0, + "Key: " + e.getKey().toString() + " | Value: " + e.getValue() + " | Type: " + + e.getValue().getClass().getName()); + } + return true; + } else { + WitcheryExtras.log(0, "Data map reflected from NBTTagCompound was not valid."); + return false; + } + } + } + } catch (Throwable t) { + } + return false; + } + + // Botania soulbind handling + public static boolean setBotanicaSoulboundOwner(ItemStack aStack, String aName) { + final String TAG_SOULBIND = "soulbind"; + NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString(TAG_SOULBIND, aName); + setNBT(aStack, tNBT); + if (NBTUtils.doesStringExist(aStack, TAG_SOULBIND)) { + return true; + } else { + return false; + } + } + + public static String getBotanicaSoulboundOwner(ItemStack aStack) { + final String TAG_SOULBIND = "soulbind"; + NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString(TAG_SOULBIND); + } + + public static boolean hasKey(ItemStack stack, String key) { + final NBTTagCompound itemData = getNBT(stack); + if (itemData.hasKey(key)) { + return true; + } + return false; + } + + public static boolean createIntegerTagCompound(ItemStack rStack, String tagName, String keyName, int keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setInteger(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createLongTagCompound(ItemStack rStack, String tagName, String keyName, long keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setLong(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createStringTagCompound(ItemStack rStack, String tagName, String keyName, String keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setString(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createFloatTagCompound(ItemStack rStack, String tagName, String keyName, float keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setFloat(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createByteTagCompound(ItemStack rStack, String tagName, String keyName, byte keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setByte(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createBooleanTagCompound(ItemStack rStack, String tagName, String keyName, boolean keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + final NBTTagCompound tagNBT = new NBTTagCompound(); + tagNBT.setBoolean(keyName, keyValue); + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static boolean createTagCompound(ItemStack rStack, String tagName, NBTTagCompound keyValue) { + final NBTTagCompound tagMain = getNBT(rStack); + NBTTagCompound tagNBT = keyValue; + tagMain.setTag(tagName, tagNBT); + rStack.setTagCompound(tagMain); + return true; + } + + public static int getIntegerTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getInteger(keyName); + } + } + return 0; + } + + public static long getLongTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getLong(keyName); + } + } + return 0L; + } + + public static String getStringTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getString(keyName); + } + } + return null; + } + + public static float getFloatTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getFloat(keyName); + } + } + return 0; + } + + public static double getByteTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getByte(keyName); + } + } + return 0; + } + + public static boolean getBooleanTagCompound(ItemStack aStack, String tagName, String keyName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT.getBoolean(keyName); + } + } + return false; + } + + public static NBTTagCompound getTagCompound(ItemStack aStack, String tagName) { + NBTTagCompound aNBT = getNBT(aStack); + if (aNBT != null && hasKey(aStack, tagName)) { + aNBT = aNBT.getCompoundTag(tagName); + if (aNBT != null) { + return aNBT; + } + } + return null; + } + + public static boolean hasKeyInTagCompound(ItemStack stack, String tag, String key) { + NBTTagCompound aNBT = stack.getTagCompound(); + if (aNBT != null) { + aNBT = aNBT.getCompoundTag(tag); + if (aNBT.hasKey(key)) { + return true; + } + } + return false; + } + + public static void setNBT(final ItemStack aStack, final NBTTagCompound aNBT) { + if (aNBT == null) { + aStack.setTagCompound((NBTTagCompound) null); + return; + } + final ArrayList tTagsToRemove = new ArrayList(); + for (final Object tKey : aNBT.func_150296_c()) { + final NBTBase tValue = aNBT.getTag((String) tKey); + if (tValue == null + || (tValue instanceof NBTBase.NBTPrimitive && ((NBTBase.NBTPrimitive) tValue).func_150291_c() == 0L) + || (tValue instanceof NBTTagString && isStringInvalid(((NBTTagString) tValue).func_150285_a_()))) { + tTagsToRemove.add((String) tKey); + } + } + for (final Object tKey : tTagsToRemove) { + aNBT.removeTag((String) tKey); + } + aStack.setTagCompound(aNBT.hasNoTags() ? null : aNBT); + } + + public static boolean isStringInvalid(final Object aString) { + return aString == null || aString.toString().isEmpty(); + } + + public static void setPunchCardData(final ItemStack aStack, final String aPunchCardData) { + final NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString("GT.PunchCardData", aPunchCardData); + setNBT(aStack, tNBT); + } + + public static String getPunchCardData(final ItemStack aStack) { + final NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString("GT.PunchCardData"); + } + + public static void setLighterFuel(final ItemStack aStack, final long aFuel) { + final NBTTagCompound tNBT = getNBT(aStack); + tNBT.setLong("GT.LighterFuel", aFuel); + setNBT(aStack, tNBT); + } + + public static long getLighterFuel(final ItemStack aStack) { + final NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getLong("GT.LighterFuel"); + } + + public static void setMapID(final ItemStack aStack, final short aMapID) { + final NBTTagCompound tNBT = getNBT(aStack); + tNBT.setShort("map_id", aMapID); + setNBT(aStack, tNBT); + } + + public static short getMapID(final ItemStack aStack) { + final NBTTagCompound tNBT = getNBT(aStack); + if (!tNBT.hasKey("map_id")) { + return -1; + } + return tNBT.getShort("map_id"); + } + + public static void setBookAuthor(final ItemStack aStack, final String aAuthor) { + final NBTTagCompound tNBT = getNBT(aStack); + tNBT.setString("author", aAuthor); + setNBT(aStack, tNBT); + } + + public static String getBookAuthor(final ItemStack aStack) { + final NBTTagCompound tNBT = getNBT(aStack); + return tNBT.getString("author"); + } + + @SuppressWarnings("unchecked") + public static V getField(final Object object, final String fieldName) { + Class clazz = object.getClass(); + while (clazz != null) { + try { + final Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + return (V) field.get(object); + } catch (final NoSuchFieldException e) { + clazz = clazz.getSuperclass(); + } catch (final Exception e) { + throw new IllegalStateException(e); + } + } + return null; + } } diff --git a/src/main/java/alkalus/main/core/util/Pair.java b/src/main/java/alkalus/main/core/util/Pair.java index 71394ad..31c33eb 100644 --- a/src/main/java/alkalus/main/core/util/Pair.java +++ b/src/main/java/alkalus/main/core/util/Pair.java @@ -2,26 +2,26 @@ import java.io.Serializable; -public class Pair implements Serializable { +public class Pair implements Serializable { - /** - * SVUID - */ - private static final long serialVersionUID = 1250550491092812443L; - private final K key; - private final V value; + /** + * SVUID + */ + private static final long serialVersionUID = 1250550491092812443L; - public Pair(final K key, final V value){ - this.key = key; - this.value = value; - } + private final K key; + private final V value; - final public K getKey(){ - return this.key; - } + public Pair(final K key, final V value) { + this.key = key; + this.value = value; + } - final public V getValue(){ - return this.value; - } + public final K getKey() { + return this.key; + } -} \ No newline at end of file + public final V getValue() { + return this.value; + } +} diff --git a/src/main/java/alkalus/main/core/util/PoppetShelfUtils.java b/src/main/java/alkalus/main/core/util/PoppetShelfUtils.java index b707ae6..0dbc56d 100644 --- a/src/main/java/alkalus/main/core/util/PoppetShelfUtils.java +++ b/src/main/java/alkalus/main/core/util/PoppetShelfUtils.java @@ -1,54 +1,65 @@ package alkalus.main.core.util; -import java.lang.reflect.Field; - +import alkalus.main.asm.AsmConfig; import com.emoniph.witchery.Witchery; import com.emoniph.witchery.blocks.BlockPoppetShelf.TileEntityPoppetShelf; import com.emoniph.witchery.util.Log; - -import alkalus.main.asm.AsmConfig; +import java.lang.reflect.Field; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.ForgeChunkManager.Ticket; import net.minecraftforge.common.ForgeChunkManager.Type; public class PoppetShelfUtils { - - private static Ticket getShelfTicket(TileEntityPoppetShelf aShelf) { - Field aChunkTicket = ReflectionUtils.getField(TileEntityPoppetShelf.class, ""); - if (aChunkTicket != null) { - return (Ticket) ReflectionUtils.getFieldValue(aChunkTicket, aShelf); - } - return null; - } - public static void initiate(TileEntityPoppetShelf aShelf) { - if (AsmConfig.allowPoppetShelfChunkLoading) { - Ticket chunkTicket = getShelfTicket(aShelf); - if(!aShelf.getWorldObj().isRemote && chunkTicket == null) { - chunkTicket = ForgeChunkManager.requestTicket(Witchery.instance, aShelf.getWorldObj(), Type.NORMAL); - if(chunkTicket != null) { - chunkTicket.getModData().setInteger("poppetX", aShelf.xCoord); - chunkTicket.getModData().setInteger("poppetY", aShelf.yCoord); - chunkTicket.getModData().setInteger("poppetZ", aShelf.zCoord); - aShelf.forceChunkLoading(chunkTicket); - } else { - Log.instance().warning(String.format("The poppet shelf at %d, %d, %d failed to register a chunk loader.", new Object[]{Integer.valueOf(aShelf.xCoord), Integer.valueOf(aShelf.yCoord), Integer.valueOf(aShelf.zCoord)})); - } - } - } - } + private static Ticket getShelfTicket(TileEntityPoppetShelf aShelf) { + Field aChunkTicket = ReflectionUtils.getField(TileEntityPoppetShelf.class, ""); + if (aChunkTicket != null) { + return (Ticket) ReflectionUtils.getFieldValue(aChunkTicket, aShelf); + } + return null; + } + + public static void initiate(TileEntityPoppetShelf aShelf) { + if (AsmConfig.allowPoppetShelfChunkLoading) { + Ticket chunkTicket = getShelfTicket(aShelf); + if (!aShelf.getWorldObj().isRemote && chunkTicket == null) { + chunkTicket = ForgeChunkManager.requestTicket(Witchery.instance, aShelf.getWorldObj(), Type.NORMAL); + if (chunkTicket != null) { + chunkTicket.getModData().setInteger("poppetX", aShelf.xCoord); + chunkTicket.getModData().setInteger("poppetY", aShelf.yCoord); + chunkTicket.getModData().setInteger("poppetZ", aShelf.zCoord); + aShelf.forceChunkLoading(chunkTicket); + } else { + Log.instance() + .warning(String.format( + "The poppet shelf at %d, %d, %d failed to register a chunk loader.", + new Object[] { + Integer.valueOf(aShelf.xCoord), + Integer.valueOf(aShelf.yCoord), + Integer.valueOf(aShelf.zCoord) + })); + } + } + } + } - public static void invalidate(TileEntityPoppetShelf aShelf) { - if(!aShelf.getWorldObj().isRemote) { - if (AsmConfig.allowPoppetShelfChunkLoading) { - Ticket chunkTicket = getShelfTicket(aShelf); - if(chunkTicket != null) { - ForgeChunkManager.releaseTicket(chunkTicket); - } else { - Log.instance().warning(String.format("Chunk loader ticket is null for poppet shelf at %d, %d, %d.", new Object[]{Integer.valueOf(aShelf.xCoord), Integer.valueOf(aShelf.yCoord), Integer.valueOf(aShelf.zCoord)})); - } - } - } - } - + public static void invalidate(TileEntityPoppetShelf aShelf) { + if (!aShelf.getWorldObj().isRemote) { + if (AsmConfig.allowPoppetShelfChunkLoading) { + Ticket chunkTicket = getShelfTicket(aShelf); + if (chunkTicket != null) { + ForgeChunkManager.releaseTicket(chunkTicket); + } else { + Log.instance() + .warning(String.format( + "Chunk loader ticket is null for poppet shelf at %d, %d, %d.", + new Object[] { + Integer.valueOf(aShelf.xCoord), + Integer.valueOf(aShelf.yCoord), + Integer.valueOf(aShelf.zCoord) + })); + } + } + } + } } diff --git a/src/main/java/alkalus/main/core/util/ReflectionUtils.java b/src/main/java/alkalus/main/core/util/ReflectionUtils.java index bc88eec..50920b5 100644 --- a/src/main/java/alkalus/main/core/util/ReflectionUtils.java +++ b/src/main/java/alkalus/main/core/util/ReflectionUtils.java @@ -1,5 +1,6 @@ package alkalus.main.core.util; +import com.google.common.reflect.ClassPath; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; @@ -15,1020 +16,979 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; - import org.apache.commons.lang3.ArrayUtils; -import com.google.common.reflect.ClassPath; - public class ReflectionUtils { - public static Map> mCachedClasses = new LinkedHashMap>(); - public static Map mCachedMethods = new LinkedHashMap(); - public static Map mCachedFields = new LinkedHashMap(); - public static Map mCachedConstructors = new LinkedHashMap(); - - private static class CachedConstructor { - - private final Constructor METHOD; - - public CachedConstructor(Constructor aCons) { - METHOD = aCons; - } - - public Constructor get() { - return METHOD; - } - - } - - private static class CachedMethod { - - private final boolean STATIC; - private final Method METHOD; - - public CachedMethod(Method aMethod, boolean isStatic) { - METHOD = aMethod; - STATIC = isStatic; - } - - public Method get() { - return METHOD; - } - - public boolean type() { - return STATIC; - } - - } - - private static class CachedField { - - private final boolean STATIC; - private final Field FIELD; - - public CachedField(Field aField, boolean isStatic) { - FIELD = aField; - STATIC = isStatic; - } - - public Field get() { - return FIELD; - } - - public boolean type() { - return STATIC; - } - - } - - private static boolean cacheClass(Class aClass) { - if (aClass == null) { - return false; - } - Class y = mCachedClasses.get(aClass.getCanonicalName()); - if (y == null) { - mCachedClasses.put(aClass.getCanonicalName(), aClass); - return true; - } - return false; - } - - private static boolean cacheMethod(Class aClass, Method aMethod) { - if (aMethod == null) { - return false; - } - boolean isStatic = Modifier.isStatic(aMethod.getModifiers()); - CachedMethod y = mCachedMethods.get(aClass.getName()+"."+aMethod.getName()+"."+ArrayUtils.toString(aMethod.getParameterTypes())); - if (y == null) { - mCachedMethods.put(aClass.getName()+"."+aMethod.getName()+"."+ArrayUtils.toString(aMethod.getParameterTypes()), new CachedMethod(aMethod, isStatic)); - return true; - } - return false; - } - - private static boolean cacheField(Class aClass, Field aField) { - if (aField == null) { - return false; - } - boolean isStatic = Modifier.isStatic(aField.getModifiers()); - CachedField y = mCachedFields.get(aClass.getName()+"."+aField.getName()); - if (y == null) { - mCachedFields.put(aClass.getName()+"."+aField.getName(), new CachedField(aField, isStatic)); - return true; - } - return false; - } - - private static boolean cacheConstructor(Class aClass, Constructor aConstructor) { - if (aConstructor == null) { - return false; - } - CachedConstructor y = mCachedConstructors.get(aClass.getName()+"."+ArrayUtils.toString(aConstructor.getParameterTypes())); - if (y == null) { - mCachedConstructors.put(aClass.getName()+"."+ArrayUtils.toString(aConstructor.getParameterTypes()), new CachedConstructor(aConstructor)); - return true; - } - return false; - } - - - /** - * Returns a cached {@link Constructor} object. - * @param aClass - Class containing the Constructor. - * @param aTypes - Varags Class Types for objects constructor. - * @return - Valid, non-final, {@link Method} object, or {@link null}. - */ - public static Constructor getConstructor(Class aClass, Class... aTypes) { - if (aClass == null || aTypes == null) { - return null; - } - - String aMethodKey = ArrayUtils.toString(aTypes); - //Logger.REFLECTION("Looking up method in cache: "+(aClass.getName()+"."+aMethodName + "." + aMethodKey)); - CachedConstructor y = mCachedConstructors.get(aClass.getName() + "." + aMethodKey); - if (y == null) { - Constructor u = getConstructor_Internal(aClass, aTypes); - if (u != null) { - Logger.REFLECTION("Caching Constructor: "+aClass.getName() + "." + aMethodKey); - cacheConstructor(aClass, u); - return u; - } else { - return null; - } - } else { - return y.get(); - } - } - - - - - /** - * Returns a cached {@link Class} object. - * @param aClassCanonicalName - The canonical name of the underlying class. - * @return - Valid, {@link Class} object, or {@link null}. - */ - public static Class getClass(String aClassCanonicalName) { - if (aClassCanonicalName == null || aClassCanonicalName.length() <= 0) { - return null; - } - Class y = mCachedClasses.get(aClassCanonicalName); - if (y == null) { - y = getClass_Internal(aClassCanonicalName); - if (y != null) { - Logger.REFLECTION("Caching Class: "+aClassCanonicalName); - cacheClass(y); - } - } - return y; - } - - - - /** - * Returns a cached {@link Method} object. Wraps {@link #getMethod(Class, String, Class...)}. - * @param aObject - Object containing the Method. - * @param aMethodName - Method's name in {@link String} form. - * @param aTypes - Class Array of Types for {@link Method}'s constructor. - * @return - Valid, non-final, {@link Method} object, or {@link null}. - */ - public static Method getMethod(Object aObject, String aMethodName, Class[] aTypes) { - return getMethod(aObject.getClass(), aMethodName, aTypes); - } - - - /** - * Returns a cached {@link Method} object. - * @param aClass - Class containing the Method. - * @param aMethodName - Method's name in {@link String} form. - * @param aTypes - Varags Class Types for {@link Method}'s constructor. - * @return - Valid, non-final, {@link Method} object, or {@link null}. - */ - public static Method getMethod(Class aClass, String aMethodName, Class... aTypes) { - if (aClass == null || aMethodName == null || aMethodName.length() <= 0) { - return null; - } - String aMethodKey = ArrayUtils.toString(aTypes); - //Logger.REFLECTION("Looking up method in cache: "+(aClass.getName()+"."+aMethodName + "." + aMethodKey)); - CachedMethod y = mCachedMethods.get(aClass.getName()+"."+aMethodName + "." + aMethodKey); - if (y == null) { - Method u = getMethod_Internal(aClass, aMethodName, aTypes); - if (u != null) { - Logger.REFLECTION("Caching Method: "+aMethodName + "." + aMethodKey); - cacheMethod(aClass, u); - return u; - } else { - return null; - } - } else { - return y.get(); - } - } - - public static boolean isStaticMethod(Class aClass, String aMethodName, Class... aTypes) { - return isStaticMethod(ReflectionUtils.getMethod(aClass, aMethodName, aTypes)); - } - - public static boolean isStaticMethod(Method aMethod) { - if (aMethod != null && Modifier.isStatic(aMethod.getModifiers())) { - return true; - } - return false; - } - - - - /** - * Returns a cached {@link Field} object. - * @param aClass - Class containing the Method. - * @param aFieldName - Field name in {@link String} form. - * @return - Valid, non-final, {@link Field} object, or {@link null}. - */ - public static Field getField(final Class aClass, final String aFieldName) { - if (aClass == null || aFieldName == null || aFieldName.length() <= 0) { - return null; - } - CachedField y = mCachedFields.get(aClass.getName()+"."+aFieldName); - if (y == null) { - Field u; - try { - u = getField_Internal(aClass, aFieldName); - if (u != null) { - Logger.REFLECTION("Caching Field '"+aFieldName+"' from "+aClass.getName()); - cacheField(aClass, u); - return u; - } - } catch (NoSuchFieldException e) { - } - return null; - - } else { - return y.get(); - } - } - - /** - * Returns a cached {@link Field} object. - * @param aInstance - {@link Object} to get the field instance from. - * @param aFieldName - Field name in {@link String} form. - * @return - Valid, non-final, {@link Field} object, or {@link null}. - */ - public static T getField(final Object aInstance, final String aFieldName) { - try { - return (T) getField(aInstance.getClass(), aFieldName).get(aInstance); - } catch (IllegalArgumentException | IllegalAccessException e) { - return null; - } - } - - - - - /* - * Utility Functions - */ - - public static boolean doesClassExist(final String classname) { - return isClassPresent(classname); - } - - - /** - * Returns the class of the objects type parameter - * @param o - Object to examine paramters on - * @return - a Class or null - */ - public static Class getTypeOfGenericObject(Object o) { - Class aTypeParam = findSuperClassParameterType(o, o.getClass(), 0); - if (aTypeParam == null) { - aTypeParam = findSubClassParameterType(o, o.getClass(), 0); - } - return aTypeParam; - } - - public static void makeFieldAccessible(final Field field) { - if (!Modifier.isPublic(field.getModifiers()) || - !Modifier.isPublic(field.getDeclaringClass().getModifiers())) - { - field.setAccessible(true); - } - } - - public static void makeMethodAccessible(final Method field) { - if (!Modifier.isPublic(field.getModifiers()) || - !Modifier.isPublic(field.getDeclaringClass().getModifiers())) - { - field.setAccessible(true); - } - } - - /** - * Get the method name for a depth in call stack.
- * Utility function - * @param depth depth in the call stack (0 means current method, 1 means call method, ...) - * @return Method name - */ - public static String getMethodName(final int depth) { - final StackTraceElement[] ste = new Throwable().getStackTrace(); - //System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName()); - return ste[depth+1].getMethodName(); - } - - - /** - * - * @param aPackageName - The full {@link Package} name in {@link String} form. - * @return - {@link Boolean} object. True if loaded > 0 classes. - */ - public static boolean dynamicallyLoadClassesInPackage(String aPackageName) { - ClassLoader classLoader = ReflectionUtils.class.getClassLoader(); - int loaded = 0; - try { - ClassPath path = ClassPath.from(classLoader); - for (ClassPath.ClassInfo info : path.getTopLevelClassesRecursive(aPackageName)) { - Class clazz = Class.forName(info.getName(), true, classLoader); - if (clazz != null) { - loaded++; - Logger.REFLECTION("Found "+clazz.getCanonicalName()+". ["+loaded+"]"); - } - } - } catch (ClassNotFoundException | IOException e) { - - } - - return loaded > 0; - } - - - - public static boolean setField(final Object object, final String fieldName, final Object fieldValue) { - Class clazz = object.getClass(); - while (clazz != null) { - try { - final Field field = getField(clazz, fieldName); - if (field != null) { - setFieldValue_Internal(object, field, fieldValue); - return true; - } - } catch (final NoSuchFieldException e) { - Logger.REFLECTION("setField("+object.toString()+", "+fieldName+") failed."); - clazz = clazz.getSuperclass(); - } catch (final Exception e) { - Logger.REFLECTION("setField("+object.toString()+", "+fieldName+") failed."); - throw new IllegalStateException(e); - } - } - return false; - - - } - - public static boolean setField(final Object object, final Field field, final Object fieldValue) { - Class clazz = object.getClass(); - while (clazz != null) { - if (clazz == Object.class) { - return false; - } - try { - final Field field2 = getField(clazz, field.getName()); - if (field2 != null) { - setFieldValue_Internal(object, field, fieldValue); - return true; - } - } catch (final NoSuchFieldException e) { - Logger.REFLECTION("setField("+object.toString()+", "+field.getName()+") failed."); - clazz = clazz.getSuperclass(); - } catch (final Exception e) { - Logger.REFLECTION("setField("+object.toString()+", "+field.getName()+") failed."); - throw new IllegalStateException(e); - } - } - return false; - } - - - /** - * Allows to change the state of an immutable instance. Huh?!? - */ - public static void setFinalFieldValue(Class clazz, String fieldName, Object newValue) { - Field nameField = getField(clazz, fieldName); - try { - setFieldValue_Internal(clazz, nameField, newValue); - } - catch (Throwable t) { - t.printStackTrace(); - } - } - - @Deprecated - public static void setFinalStatic(Field field, Object newValue) throws Exception { - field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - field.set(null, newValue); - } - - - public static void setByte(Object clazz, String fieldName, byte newValue) throws Exception { - Field nameField = getField(clazz.getClass(), fieldName); - nameField.setAccessible(true); - int modifiers = nameField.getModifiers(); - Field modifierField = nameField.getClass().getDeclaredField("modifiers"); - modifiers = modifiers & ~Modifier.FINAL; - modifierField.setAccessible(true); - modifierField.setInt(nameField, modifiers); - //Utils.LOG_INFO("O-"+(byte) nameField.get(clazz) + " | "+newValue); - nameField.setByte(clazz, newValue); - //Utils.LOG_INFO("N-"+(byte) nameField.get(clazz)); - - /*final Field fieldA = getField(clazz.getClass(), fieldName); - fieldA.setAccessible(true); - fieldA.setByte(clazz, newValue);*/ - - } - - public static boolean invoke(Object objectInstance, String methodName, Class[] parameters, Object[] values){ - if (objectInstance == null || methodName == null || parameters == null || values == null){ - return false; - } - Class mLocalClass = (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); - Logger.REFLECTION("Trying to invoke "+methodName+" on an instance of "+mLocalClass.getCanonicalName()+"."); - try { - Method mInvokingMethod = mLocalClass.getDeclaredMethod(methodName, parameters); - if (mInvokingMethod != null){ - return invoke(objectInstance, mInvokingMethod, values); - } - } - catch (NoSuchMethodException | SecurityException | IllegalArgumentException e) { - Logger.REFLECTION("Failed to Dynamically invoke "+methodName+" on an object of type: "+mLocalClass.getName()); - } - - Logger.REFLECTION("Invoke failed or did something wrong."); - return false; - } - - public static boolean invoke(Object objectInstance, Method method, Object[] values){ - if (method == null || values == null || (!ReflectionUtils.isStaticMethod(method) && objectInstance == null)){ - //Logger.REFLECTION("Null value when trying to Dynamically invoke "+methodName+" on an object of type: "+objectInstance.getClass().getName()); - return false; - } - String methodName = method.getName(); - String classname = objectInstance != null ? objectInstance.getClass().getCanonicalName() : method.getDeclaringClass().getCanonicalName(); - Logger.REFLECTION("Trying to invoke "+methodName+" on an instance of "+classname+"."); - try { - Method mInvokingMethod = method; - if (mInvokingMethod != null){ - Logger.REFLECTION(methodName+" was not null."); - if ((boolean) mInvokingMethod.invoke(objectInstance, values)){ - Logger.REFLECTION("Successfully invoked "+methodName+"."); - return true; - } - else { - Logger.REFLECTION("Invocation failed for "+methodName+"."); - } - } - } - catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - Logger.REFLECTION("Failed to Dynamically invoke "+methodName+" on an object of type: "+classname); - } - Logger.REFLECTION("Invoke failed or did something wrong."); - return false; - } - - public static boolean invokeVoid(Object objectInstance, String methodName, Class[] parameters, Object[] values){ - if (objectInstance == null || methodName == null || parameters == null || values == null){ - return false; - } - Class mLocalClass = (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); - Logger.REFLECTION("Trying to invoke "+methodName+" on an instance of "+mLocalClass.getCanonicalName()+"."); - try { - Method mInvokingMethod = mLocalClass.getDeclaredMethod(methodName, parameters); - if (mInvokingMethod != null){ - Logger.REFLECTION(methodName+" was not null."); - mInvokingMethod.invoke(objectInstance, values); - Logger.REFLECTION("Successfully invoked "+methodName+"."); - return true; - } - else { - Logger.REFLECTION(methodName+" is null."); - } - } - catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - Logger.REFLECTION("Failed to Dynamically invoke "+methodName+" on an object of type: "+mLocalClass.getName()); - } - - Logger.REFLECTION("Invoke failed or did something wrong."); - return false; - } - - public static Object invokeNonBool(Object objectInstance, String methodName, Class[] parameters, Object[] values){ - if (objectInstance == null || methodName == null || parameters == null || values == null){ - return false; - } - Class mLocalClass = (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); - Logger.REFLECTION("Trying to invoke "+methodName+" on an instance of "+mLocalClass.getCanonicalName()+"."); - try { - Method mInvokingMethod = mLocalClass.getDeclaredMethod(methodName, parameters); - if (mInvokingMethod != null){ - Logger.REFLECTION(methodName+" was not null."); - return mInvokingMethod.invoke(objectInstance, values); - } - else { - Logger.REFLECTION(methodName+" is null."); - } - } - catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - Logger.REFLECTION("Failed to Dynamically invoke "+methodName+" on an object of type: "+mLocalClass.getName()); - } - - Logger.REFLECTION("Invoke failed or did something wrong."); - return null; - } - - - public static Object invokeNonVoid(Object aInstance, Method aMethod){ - return invokeNonVoid(aInstance, aMethod, new Object[] {}); - } - - public static Object invokeNonVoid(Object aInstance, Method aMethod, Object[] aValues){ - if (aMethod == null || (!ReflectionUtils.isStaticMethod(aMethod) && aInstance == null) || aValues == null){ - return false; - } - try { - return aMethod.invoke(aInstance, aValues); - } - catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - Logger.REFLECTION("Failed to Dynamically invoke "+aMethod.getName()+" on an object of type: "+aInstance.getClass().getName()); - e.printStackTrace(); - } - Logger.REFLECTION("Invoke failed or did something wrong."); - return null; - } - - - - - - - - - - - - - - - - - - - - /* - * Internal Magic that probably should not get exposed. - */ - - - - - - - - - - /* - * - * Below Code block is used for determining generic types associated with type - * - */ - - - //https://xebia.com/blog/acessing-generic-types-at-runtime-in-java/ - //https://www.javacodegeeks.com/2013/12/advanced-java-generics-retreiving-generic-type-arguments.html - public static Class findSuperClassParameterType(Object instance, Class classOfInterest, int parameterIndex) { - Class subClass = instance.getClass(); - while (classOfInterest != subClass.getSuperclass()) { - // instance.getClass() is no subclass of classOfInterest or instance is a direct instance of classOfInterest - subClass = subClass.getSuperclass(); - if (subClass == null) { - return null; - } - } - ParameterizedType parameterizedType = (ParameterizedType) subClass.getGenericSuperclass(); - Class aReturn; - aReturn = (Class) parameterizedType.getActualTypeArguments()[parameterIndex]; - return aReturn; - } - - public static Class findSubClassParameterType(Object instance, Class classOfInterest, int parameterIndex) { - Map typeMap = new HashMap(); - Class instanceClass = instance.getClass(); - while (classOfInterest != instanceClass.getSuperclass()) { - extractTypeArguments(typeMap, instanceClass); - instanceClass = instanceClass.getSuperclass(); - if (instanceClass == null) { - return null; - } - } - - ParameterizedType parameterizedType = (ParameterizedType) instanceClass.getGenericSuperclass(); - Type actualType = parameterizedType.getActualTypeArguments()[parameterIndex]; - if (typeMap.containsKey(actualType)) { - actualType = typeMap.get(actualType); - } - if (actualType instanceof Class) { - return (Class) actualType; - } else if (actualType instanceof TypeVariable) { - return browseNestedTypes(instance, (TypeVariable) actualType); - } else { - return null; - } - } - - private static void extractTypeArguments(Map typeMap, Class clazz) { - Type genericSuperclass = clazz.getGenericSuperclass(); - if (!(genericSuperclass instanceof ParameterizedType)) { - return; - } - - ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; - Type[] typeParameter = ((Class) parameterizedType.getRawType()).getTypeParameters(); - Type[] actualTypeArgument = parameterizedType.getActualTypeArguments(); - for (int i = 0; i < typeParameter.length; i++) { - if(typeMap.containsKey(actualTypeArgument[i])) { - actualTypeArgument[i] = typeMap.get(actualTypeArgument[i]); - } - typeMap.put(typeParameter[i], actualTypeArgument[i]); - } - } - - private static Class browseNestedTypes(Object instance, TypeVariable actualType) { - Class instanceClass = instance.getClass(); - List> nestedOuterTypes = new LinkedList>(); - for (Class enclosingClass = instanceClass - .getEnclosingClass(); enclosingClass != null; enclosingClass = enclosingClass.getEnclosingClass()) { - try { - Field this$0 = instanceClass.getDeclaredField("this$0"); - Object outerInstance = this$0.get(instance); - Class outerClass = outerInstance.getClass(); - nestedOuterTypes.add(outerClass); - Map outerTypeMap = new HashMap(); - extractTypeArguments(outerTypeMap, outerClass); - for (Map.Entry entry : outerTypeMap.entrySet()) { - if (!(entry.getKey() instanceof TypeVariable)) { - continue; - } - TypeVariable foundType = (TypeVariable) entry.getKey(); - if (foundType.getName().equals(actualType.getName()) - && isInnerClass(foundType.getGenericDeclaration(), actualType.getGenericDeclaration())) { - if (entry.getValue() instanceof Class) { - return (Class) entry.getValue(); - } - actualType = (TypeVariable) entry.getValue(); - } - } - } catch (NoSuchFieldException | IllegalAccessException e) { - - } - - } - return null; - } - - private static boolean isInnerClass(GenericDeclaration outerDeclaration, GenericDeclaration innerDeclaration) { - if (!(outerDeclaration instanceof Class) || !(innerDeclaration instanceof Class)) { - return false; - } - Class outerClass = (Class) outerDeclaration; - Class innerClass = (Class) innerDeclaration; - while ((innerClass = innerClass.getEnclosingClass()) != null) { - if (innerClass == outerClass) { - return true; - } - } - return false; - } - - - /* - * - * End of Generics Block - * - */ - - - - private static Field getField_Internal(final Class clazz, final String fieldName) throws NoSuchFieldException { - try { - Logger.REFLECTION("Field: Internal Lookup: "+fieldName); - Field k = clazz.getDeclaredField(fieldName); - makeFieldAccessible(k); - //Logger.REFLECTION("Got Field from Class. "+fieldName+" did exist within "+clazz.getCanonicalName()+"."); - return k; - } catch (final NoSuchFieldException e) { - Logger.REFLECTION("Field: Internal Lookup Failed: "+fieldName); - final Class superClass = clazz.getSuperclass(); - if (superClass == null) { - Logger.REFLECTION("Unable to find field '"+fieldName+"'"); - //Logger.REFLECTION("Failed to get Field from Class. "+fieldName+" does not existing within "+clazz.getCanonicalName()+"."); - throw e; - } - Logger.REFLECTION("Method: Recursion Lookup: "+fieldName+" - Checking in "+superClass.getName()); - //Logger.REFLECTION("Failed to get Field from Class. "+fieldName+" does not existing within "+clazz.getCanonicalName()+". Trying super class."); - return getField_Internal(superClass, fieldName); - } - } - - /** - * if (isPresent("com.optionaldependency.DependencyClass")) || - * This block will never execute when the dependency is not present. There is - * therefore no more risk of code throwing NoClassDefFoundException. - */ - private static boolean isClassPresent(final String className) { - try { - Class.forName(className); - return true; - } catch (final Throwable ex) { - // Class or one of its dependencies is not present... - return false; - } - } - - @Deprecated - public static Method getMethodViaReflection(final Class lookupClass, final String methodName, - final boolean invoke) throws Exception { - final Class lookup = lookupClass.getClass(); - final Method m = lookup.getDeclaredMethod(methodName); - m.setAccessible(true);// Abracadabra - if (invoke) { - m.invoke(lookup);// now its OK - } - return m; - } - - private static Method getMethod_Internal(Class aClass, String aMethodName, Class... aTypes) { - Method m = null; - try { - Logger.REFLECTION("Method: Internal Lookup: "+aMethodName); - m = aClass.getDeclaredMethod(aMethodName, aTypes); - if (m != null) { - m.setAccessible(true); - int modifiers = m.getModifiers(); - Field modifierField = m.getClass().getDeclaredField("modifiers"); - modifiers = modifiers & ~Modifier.FINAL; - modifierField.setAccessible(true); - modifierField.setInt(m, modifiers); - } - } - catch (Throwable t) { - Logger.REFLECTION("Method: Internal Lookup Failed: "+aMethodName); - try { - m = getMethodRecursively(aClass, aMethodName); - } catch (NoSuchMethodException e) { - Logger.REFLECTION("Unable to find method '"+aMethodName+"'"); - e.printStackTrace(); - dumpClassInfo(aClass); - } - } - return m; - } - - private static Constructor getConstructor_Internal(Class aClass, Class... aTypes) { - Constructor c = null; - try { - Logger.REFLECTION("Constructor: Internal Lookup: "+aClass.getName()); - c = aClass.getDeclaredConstructor(aTypes); - if (c != null) { - c.setAccessible(true); - int modifiers = c.getModifiers(); - Field modifierField = c.getClass().getDeclaredField("modifiers"); - modifiers = modifiers & ~Modifier.FINAL; - modifierField.setAccessible(true); - modifierField.setInt(c, modifiers); - } - } - catch (Throwable t) { - Logger.REFLECTION("Constructor: Internal Lookup Failed: "+aClass.getName()); - try { - c = getConstructorRecursively(aClass, aTypes); - } catch (Exception e) { - Logger.REFLECTION("Unable to find method '"+aClass.getName()+"'"); - e.printStackTrace(); - dumpClassInfo(aClass); - } - } - return c; - } - - private static Constructor getConstructorRecursively(Class aClass, Class... aTypes) throws Exception { - try { - Logger.REFLECTION("Constructor: Recursion Lookup: "+aClass.getName()); - Constructor c = aClass.getConstructor(aTypes); - if (c != null) { - c.setAccessible(true); - int modifiers = c.getModifiers(); - Field modifierField = c.getClass().getDeclaredField("modifiers"); - modifiers = modifiers & ~Modifier.FINAL; - modifierField.setAccessible(true); - modifierField.setInt(c, modifiers); - } - return c; - } catch (final NoSuchMethodException | IllegalArgumentException | IllegalAccessException e) { - final Class superClass = aClass.getSuperclass(); - if (superClass == null || superClass == Object.class) { - throw e; - } - return getConstructor_Internal(superClass, aTypes); - } - } - - private static Method getMethodRecursively(final Class clazz, final String aMethodName) throws NoSuchMethodException { - try { - Logger.REFLECTION("Method: Recursion Lookup: "+aMethodName); - Method k = clazz.getDeclaredMethod(aMethodName); - makeMethodAccessible(k); - return k; - } catch (final NoSuchMethodException e) { - final Class superClass = clazz.getSuperclass(); - if (superClass == null || superClass == Object.class) { - throw e; - } - return getMethod_Internal(superClass, aMethodName); - } - } - - private static void dumpClassInfo(Class aClass) { - Logger.REFLECTION("We ran into an error processing reflection in "+aClass.getName()+", dumping all data for debugging."); - // Get the methods - Method[] methods = aClass.getDeclaredMethods(); - Field[] fields = aClass.getDeclaredFields(); - Constructor[] consts = aClass.getDeclaredConstructors(); - - Logger.REFLECTION("Dumping all Methods."); - for (Method method : methods) { - System.out.println(method.getName()+" | "+getDataStringFromArray(method.getParameterTypes())); - } - Logger.REFLECTION("Dumping all Fields."); - for (Field f : fields) { - System.out.println(f.getName()); - } - Logger.REFLECTION("Dumping all Constructors."); - for (Constructor c : consts) { - System.out.println(c.getName()+" | "+c.getParameterCount()+" | "+getDataStringFromArray(c.getParameterTypes())); - } - } - - private static Class getNonPublicClass(final String className) { - Class c = null; - try { - c = Class.forName(className); - } catch (final ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // full package name --------^^^^^^^^^^ - // or simpler without Class.forName: - // Class c = package1.A.class; - - if (null != c) { - // In our case we need to use - Constructor constructor = null; - try { - constructor = c.getDeclaredConstructor(); - } catch (NoSuchMethodException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // note: getConstructor() can return only public constructors - // so we needed to search for any Declared constructor - - // now we need to make this constructor accessible - if (null != constructor) { - constructor.setAccessible(true);// ABRACADABRA! - - try { - final Object o = constructor.newInstance(); - return (Class) o; - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - return null; - } - - private static Class getClass_Internal(String string) { - Class aClass = null; - if (ReflectionUtils.doesClassExist(string)) { - try { - aClass = Class.forName(string); - } - catch (ClassNotFoundException e) { - aClass = getNonPublicClass(string); - } - } - - if (aClass == null) { - String aClassName = ""; - Logger.REFLECTION("Splitting "+string+" to try look for hidden classes."); - String[] aData = string.split("\\."); - Logger.REFLECTION("Obtained "+aData.length+" pieces."); - for (int i=0;i<(aData.length-1);i++) { - aClassName += (i > 0) ? "."+aData[i] : ""+aData[i]; - Logger.REFLECTION("Building: "+aClassName); - } - Logger.REFLECTION("Trying to search '"+aClassName+"' for inner classes."); - Class clazz = ReflectionUtils.getClass(aClassName); - - Class[] y = clazz.getDeclaredClasses(); - if (y == null || y.length <= 0) { - Logger.REFLECTION("No hidden inner classes found."); - return null; - } - else { - boolean found = false; - for (Class h : y) { - Logger.REFLECTION("Found hidden inner class: "+h.getCanonicalName()); - if (h.getSimpleName().toLowerCase().equals(aData[aData.length-1].toLowerCase())) { - Logger.REFLECTION("Found correct class. ["+aData[aData.length-1]+"] Caching at correct location: "+string); - Logger.REFLECTION("Found at location: "+h.getCanonicalName()); - ReflectionUtils.mCachedClasses.put(string, h); - aClass = h; - found = true; - break; - } - } - if (!found) { - return null; - } - } - } - return aClass; - } - - /** - * - * Set the value of a field reflectively. - */ - private static void setFieldValue_Internal(Object owner, Field field, Object value) throws Exception { - makeModifiable(field); - field.set(owner, value); - } - - /** - * Force the field to be modifiable and accessible. - */ - private static void makeModifiable(Field nameField) throws Exception { - nameField.setAccessible(true); - int modifiers = nameField.getModifiers(); - Field modifierField = nameField.getClass().getDeclaredField("modifiers"); - modifiers = modifiers & ~Modifier.FINAL; - modifierField.setAccessible(true); - modifierField.setInt(nameField, modifiers); - } - - - public static boolean doesFieldExist(String clazz, String string) { - return doesFieldExist(ReflectionUtils.getClass(clazz), string); - } - - public static boolean doesFieldExist(Class clazz, String string) { - if (clazz != null) { - if (ReflectionUtils.getField(clazz, string) != null) { - return true; - } - } - return false; - } - - public static Object getFieldValue(Field field) { - return getFieldValue(field, null); - } - - public static Object getFieldValue(Field field, Object instance) { - try { - return field.get(instance); - } catch (IllegalArgumentException | IllegalAccessException e) { - } - return null; - } - - private static final String getDataStringFromArray(V[] parameterTypes) { - if (parameterTypes == null || parameterTypes.length == 0) { - return "empty/null"; - } - else { - String aData = ""; - for (V y : parameterTypes) { - if (y != null) { - aData += ", "+y.toString(); - } - } - return aData; - } - } - - + public static Map> mCachedClasses = new LinkedHashMap>(); + public static Map mCachedMethods = new LinkedHashMap(); + public static Map mCachedFields = new LinkedHashMap(); + public static Map mCachedConstructors = new LinkedHashMap(); + + private static class CachedConstructor { + + private final Constructor METHOD; + + public CachedConstructor(Constructor aCons) { + METHOD = aCons; + } + + public Constructor get() { + return METHOD; + } + } + + private static class CachedMethod { + + private final boolean STATIC; + private final Method METHOD; + + public CachedMethod(Method aMethod, boolean isStatic) { + METHOD = aMethod; + STATIC = isStatic; + } + + public Method get() { + return METHOD; + } + + public boolean type() { + return STATIC; + } + } + + private static class CachedField { + + private final boolean STATIC; + private final Field FIELD; + + public CachedField(Field aField, boolean isStatic) { + FIELD = aField; + STATIC = isStatic; + } + + public Field get() { + return FIELD; + } + + public boolean type() { + return STATIC; + } + } + + private static boolean cacheClass(Class aClass) { + if (aClass == null) { + return false; + } + Class y = mCachedClasses.get(aClass.getCanonicalName()); + if (y == null) { + mCachedClasses.put(aClass.getCanonicalName(), aClass); + return true; + } + return false; + } + + private static boolean cacheMethod(Class aClass, Method aMethod) { + if (aMethod == null) { + return false; + } + boolean isStatic = Modifier.isStatic(aMethod.getModifiers()); + CachedMethod y = mCachedMethods.get( + aClass.getName() + "." + aMethod.getName() + "." + ArrayUtils.toString(aMethod.getParameterTypes())); + if (y == null) { + mCachedMethods.put( + aClass.getName() + "." + aMethod.getName() + "." + ArrayUtils.toString(aMethod.getParameterTypes()), + new CachedMethod(aMethod, isStatic)); + return true; + } + return false; + } + + private static boolean cacheField(Class aClass, Field aField) { + if (aField == null) { + return false; + } + boolean isStatic = Modifier.isStatic(aField.getModifiers()); + CachedField y = mCachedFields.get(aClass.getName() + "." + aField.getName()); + if (y == null) { + mCachedFields.put(aClass.getName() + "." + aField.getName(), new CachedField(aField, isStatic)); + return true; + } + return false; + } + + private static boolean cacheConstructor(Class aClass, Constructor aConstructor) { + if (aConstructor == null) { + return false; + } + CachedConstructor y = + mCachedConstructors.get(aClass.getName() + "." + ArrayUtils.toString(aConstructor.getParameterTypes())); + if (y == null) { + mCachedConstructors.put( + aClass.getName() + "." + ArrayUtils.toString(aConstructor.getParameterTypes()), + new CachedConstructor(aConstructor)); + return true; + } + return false; + } + + /** + * Returns a cached {@link Constructor} object. + * @param aClass - Class containing the Constructor. + * @param aTypes - Varags Class Types for objects constructor. + * @return - Valid, non-final, {@link Method} object, or {@link null}. + */ + public static Constructor getConstructor(Class aClass, Class... aTypes) { + if (aClass == null || aTypes == null) { + return null; + } + + String aMethodKey = ArrayUtils.toString(aTypes); + // Logger.REFLECTION("Looking up method in cache: "+(aClass.getName()+"."+aMethodName + "." + aMethodKey)); + CachedConstructor y = mCachedConstructors.get(aClass.getName() + "." + aMethodKey); + if (y == null) { + Constructor u = getConstructor_Internal(aClass, aTypes); + if (u != null) { + Logger.REFLECTION("Caching Constructor: " + aClass.getName() + "." + aMethodKey); + cacheConstructor(aClass, u); + return u; + } else { + return null; + } + } else { + return y.get(); + } + } + + /** + * Returns a cached {@link Class} object. + * @param aClassCanonicalName - The canonical name of the underlying class. + * @return - Valid, {@link Class} object, or {@link null}. + */ + public static Class getClass(String aClassCanonicalName) { + if (aClassCanonicalName == null || aClassCanonicalName.length() <= 0) { + return null; + } + Class y = mCachedClasses.get(aClassCanonicalName); + if (y == null) { + y = getClass_Internal(aClassCanonicalName); + if (y != null) { + Logger.REFLECTION("Caching Class: " + aClassCanonicalName); + cacheClass(y); + } + } + return y; + } + + /** + * Returns a cached {@link Method} object. Wraps {@link #getMethod(Class, String, Class...)}. + * @param aObject - Object containing the Method. + * @param aMethodName - Method's name in {@link String} form. + * @param aTypes - Class Array of Types for {@link Method}'s constructor. + * @return - Valid, non-final, {@link Method} object, or {@link null}. + */ + public static Method getMethod(Object aObject, String aMethodName, Class[] aTypes) { + return getMethod(aObject.getClass(), aMethodName, aTypes); + } + + /** + * Returns a cached {@link Method} object. + * @param aClass - Class containing the Method. + * @param aMethodName - Method's name in {@link String} form. + * @param aTypes - Varags Class Types for {@link Method}'s constructor. + * @return - Valid, non-final, {@link Method} object, or {@link null}. + */ + public static Method getMethod(Class aClass, String aMethodName, Class... aTypes) { + if (aClass == null || aMethodName == null || aMethodName.length() <= 0) { + return null; + } + String aMethodKey = ArrayUtils.toString(aTypes); + // Logger.REFLECTION("Looking up method in cache: "+(aClass.getName()+"."+aMethodName + "." + aMethodKey)); + CachedMethod y = mCachedMethods.get(aClass.getName() + "." + aMethodName + "." + aMethodKey); + if (y == null) { + Method u = getMethod_Internal(aClass, aMethodName, aTypes); + if (u != null) { + Logger.REFLECTION("Caching Method: " + aMethodName + "." + aMethodKey); + cacheMethod(aClass, u); + return u; + } else { + return null; + } + } else { + return y.get(); + } + } + + public static boolean isStaticMethod(Class aClass, String aMethodName, Class... aTypes) { + return isStaticMethod(ReflectionUtils.getMethod(aClass, aMethodName, aTypes)); + } + + public static boolean isStaticMethod(Method aMethod) { + if (aMethod != null && Modifier.isStatic(aMethod.getModifiers())) { + return true; + } + return false; + } + + /** + * Returns a cached {@link Field} object. + * @param aClass - Class containing the Method. + * @param aFieldName - Field name in {@link String} form. + * @return - Valid, non-final, {@link Field} object, or {@link null}. + */ + public static Field getField(final Class aClass, final String aFieldName) { + if (aClass == null || aFieldName == null || aFieldName.length() <= 0) { + return null; + } + CachedField y = mCachedFields.get(aClass.getName() + "." + aFieldName); + if (y == null) { + Field u; + try { + u = getField_Internal(aClass, aFieldName); + if (u != null) { + Logger.REFLECTION("Caching Field '" + aFieldName + "' from " + aClass.getName()); + cacheField(aClass, u); + return u; + } + } catch (NoSuchFieldException e) { + } + return null; + + } else { + return y.get(); + } + } + + /** + * Returns a cached {@link Field} object. + * @param aInstance - {@link Object} to get the field instance from. + * @param aFieldName - Field name in {@link String} form. + * @return - Valid, non-final, {@link Field} object, or {@link null}. + */ + public static T getField(final Object aInstance, final String aFieldName) { + try { + return (T) getField(aInstance.getClass(), aFieldName).get(aInstance); + } catch (IllegalArgumentException | IllegalAccessException e) { + return null; + } + } + + /* + * Utility Functions + */ + + public static boolean doesClassExist(final String classname) { + return isClassPresent(classname); + } + + /** + * Returns the class of the objects type parameter + * @param o - Object to examine paramters on + * @return - a Class or null + */ + public static Class getTypeOfGenericObject(Object o) { + Class aTypeParam = findSuperClassParameterType(o, o.getClass(), 0); + if (aTypeParam == null) { + aTypeParam = findSubClassParameterType(o, o.getClass(), 0); + } + return aTypeParam; + } + + public static void makeFieldAccessible(final Field field) { + if (!Modifier.isPublic(field.getModifiers()) + || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { + field.setAccessible(true); + } + } + + public static void makeMethodAccessible(final Method field) { + if (!Modifier.isPublic(field.getModifiers()) + || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { + field.setAccessible(true); + } + } + + /** + * Get the method name for a depth in call stack.
+ * Utility function + * @param depth depth in the call stack (0 means current method, 1 means call method, ...) + * @return Method name + */ + public static String getMethodName(final int depth) { + final StackTraceElement[] ste = new Throwable().getStackTrace(); + // System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName()); + return ste[depth + 1].getMethodName(); + } + + /** + * + * @param aPackageName - The full {@link Package} name in {@link String} form. + * @return - {@link Boolean} object. True if loaded > 0 classes. + */ + public static boolean dynamicallyLoadClassesInPackage(String aPackageName) { + ClassLoader classLoader = ReflectionUtils.class.getClassLoader(); + int loaded = 0; + try { + ClassPath path = ClassPath.from(classLoader); + for (ClassPath.ClassInfo info : path.getTopLevelClassesRecursive(aPackageName)) { + Class clazz = Class.forName(info.getName(), true, classLoader); + if (clazz != null) { + loaded++; + Logger.REFLECTION("Found " + clazz.getCanonicalName() + ". [" + loaded + "]"); + } + } + } catch (ClassNotFoundException | IOException e) { + + } + + return loaded > 0; + } + + public static boolean setField(final Object object, final String fieldName, final Object fieldValue) { + Class clazz = object.getClass(); + while (clazz != null) { + try { + final Field field = getField(clazz, fieldName); + if (field != null) { + setFieldValue_Internal(object, field, fieldValue); + return true; + } + } catch (final NoSuchFieldException e) { + Logger.REFLECTION("setField(" + object.toString() + ", " + fieldName + ") failed."); + clazz = clazz.getSuperclass(); + } catch (final Exception e) { + Logger.REFLECTION("setField(" + object.toString() + ", " + fieldName + ") failed."); + throw new IllegalStateException(e); + } + } + return false; + } + + public static boolean setField(final Object object, final Field field, final Object fieldValue) { + Class clazz = object.getClass(); + while (clazz != null) { + if (clazz == Object.class) { + return false; + } + try { + final Field field2 = getField(clazz, field.getName()); + if (field2 != null) { + setFieldValue_Internal(object, field, fieldValue); + return true; + } + } catch (final NoSuchFieldException e) { + Logger.REFLECTION("setField(" + object.toString() + ", " + field.getName() + ") failed."); + clazz = clazz.getSuperclass(); + } catch (final Exception e) { + Logger.REFLECTION("setField(" + object.toString() + ", " + field.getName() + ") failed."); + throw new IllegalStateException(e); + } + } + return false; + } + + /** + * Allows to change the state of an immutable instance. Huh?!? + */ + public static void setFinalFieldValue(Class clazz, String fieldName, Object newValue) { + Field nameField = getField(clazz, fieldName); + try { + setFieldValue_Internal(clazz, nameField, newValue); + } catch (Throwable t) { + t.printStackTrace(); + } + } + + @Deprecated + public static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(null, newValue); + } + + public static void setByte(Object clazz, String fieldName, byte newValue) throws Exception { + Field nameField = getField(clazz.getClass(), fieldName); + nameField.setAccessible(true); + int modifiers = nameField.getModifiers(); + Field modifierField = nameField.getClass().getDeclaredField("modifiers"); + modifiers = modifiers & ~Modifier.FINAL; + modifierField.setAccessible(true); + modifierField.setInt(nameField, modifiers); + // Utils.LOG_INFO("O-"+(byte) nameField.get(clazz) + " | "+newValue); + nameField.setByte(clazz, newValue); + // Utils.LOG_INFO("N-"+(byte) nameField.get(clazz)); + + /*final Field fieldA = getField(clazz.getClass(), fieldName); + fieldA.setAccessible(true); + fieldA.setByte(clazz, newValue);*/ + + } + + public static boolean invoke(Object objectInstance, String methodName, Class[] parameters, Object[] values) { + if (objectInstance == null || methodName == null || parameters == null || values == null) { + return false; + } + Class mLocalClass = + (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); + Logger.REFLECTION( + "Trying to invoke " + methodName + " on an instance of " + mLocalClass.getCanonicalName() + "."); + try { + Method mInvokingMethod = mLocalClass.getDeclaredMethod(methodName, parameters); + if (mInvokingMethod != null) { + return invoke(objectInstance, mInvokingMethod, values); + } + } catch (NoSuchMethodException | SecurityException | IllegalArgumentException e) { + Logger.REFLECTION( + "Failed to Dynamically invoke " + methodName + " on an object of type: " + mLocalClass.getName()); + } + + Logger.REFLECTION("Invoke failed or did something wrong."); + return false; + } + + public static boolean invoke(Object objectInstance, Method method, Object[] values) { + if (method == null || values == null || (!ReflectionUtils.isStaticMethod(method) && objectInstance == null)) { + // Logger.REFLECTION("Null value when trying to Dynamically invoke "+methodName+" on an object of type: + // "+objectInstance.getClass().getName()); + return false; + } + String methodName = method.getName(); + String classname = objectInstance != null + ? objectInstance.getClass().getCanonicalName() + : method.getDeclaringClass().getCanonicalName(); + Logger.REFLECTION("Trying to invoke " + methodName + " on an instance of " + classname + "."); + try { + Method mInvokingMethod = method; + if (mInvokingMethod != null) { + Logger.REFLECTION(methodName + " was not null."); + if ((boolean) mInvokingMethod.invoke(objectInstance, values)) { + Logger.REFLECTION("Successfully invoked " + methodName + "."); + return true; + } else { + Logger.REFLECTION("Invocation failed for " + methodName + "."); + } + } + } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + Logger.REFLECTION("Failed to Dynamically invoke " + methodName + " on an object of type: " + classname); + } + Logger.REFLECTION("Invoke failed or did something wrong."); + return false; + } + + public static boolean invokeVoid(Object objectInstance, String methodName, Class[] parameters, Object[] values) { + if (objectInstance == null || methodName == null || parameters == null || values == null) { + return false; + } + Class mLocalClass = + (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); + Logger.REFLECTION( + "Trying to invoke " + methodName + " on an instance of " + mLocalClass.getCanonicalName() + "."); + try { + Method mInvokingMethod = mLocalClass.getDeclaredMethod(methodName, parameters); + if (mInvokingMethod != null) { + Logger.REFLECTION(methodName + " was not null."); + mInvokingMethod.invoke(objectInstance, values); + Logger.REFLECTION("Successfully invoked " + methodName + "."); + return true; + } else { + Logger.REFLECTION(methodName + " is null."); + } + } catch (NoSuchMethodException + | SecurityException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException e) { + Logger.REFLECTION( + "Failed to Dynamically invoke " + methodName + " on an object of type: " + mLocalClass.getName()); + } + + Logger.REFLECTION("Invoke failed or did something wrong."); + return false; + } + + public static Object invokeNonBool(Object objectInstance, String methodName, Class[] parameters, Object[] values) { + if (objectInstance == null || methodName == null || parameters == null || values == null) { + return false; + } + Class mLocalClass = + (objectInstance instanceof Class ? (Class) objectInstance : objectInstance.getClass()); + Logger.REFLECTION( + "Trying to invoke " + methodName + " on an instance of " + mLocalClass.getCanonicalName() + "."); + try { + Method mInvokingMethod = mLocalClass.getDeclaredMethod(methodName, parameters); + if (mInvokingMethod != null) { + Logger.REFLECTION(methodName + " was not null."); + return mInvokingMethod.invoke(objectInstance, values); + } else { + Logger.REFLECTION(methodName + " is null."); + } + } catch (NoSuchMethodException + | SecurityException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException e) { + Logger.REFLECTION( + "Failed to Dynamically invoke " + methodName + " on an object of type: " + mLocalClass.getName()); + } + + Logger.REFLECTION("Invoke failed or did something wrong."); + return null; + } + + public static Object invokeNonVoid(Object aInstance, Method aMethod) { + return invokeNonVoid(aInstance, aMethod, new Object[] {}); + } + + public static Object invokeNonVoid(Object aInstance, Method aMethod, Object[] aValues) { + if (aMethod == null || (!ReflectionUtils.isStaticMethod(aMethod) && aInstance == null) || aValues == null) { + return false; + } + try { + return aMethod.invoke(aInstance, aValues); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + Logger.REFLECTION("Failed to Dynamically invoke " + aMethod.getName() + " on an object of type: " + + aInstance.getClass().getName()); + e.printStackTrace(); + } + Logger.REFLECTION("Invoke failed or did something wrong."); + return null; + } + + /* + * Internal Magic that probably should not get exposed. + */ + + /* + * + * Below Code block is used for determining generic types associated with type + * + */ + + // https://xebia.com/blog/acessing-generic-types-at-runtime-in-java/ + // https://www.javacodegeeks.com/2013/12/advanced-java-generics-retreiving-generic-type-arguments.html + public static Class findSuperClassParameterType(Object instance, Class classOfInterest, int parameterIndex) { + Class subClass = instance.getClass(); + while (classOfInterest != subClass.getSuperclass()) { + // instance.getClass() is no subclass of classOfInterest or instance is a direct instance of classOfInterest + subClass = subClass.getSuperclass(); + if (subClass == null) { + return null; + } + } + ParameterizedType parameterizedType = (ParameterizedType) subClass.getGenericSuperclass(); + Class aReturn; + aReturn = (Class) parameterizedType.getActualTypeArguments()[parameterIndex]; + return aReturn; + } + + public static Class findSubClassParameterType(Object instance, Class classOfInterest, int parameterIndex) { + Map typeMap = new HashMap(); + Class instanceClass = instance.getClass(); + while (classOfInterest != instanceClass.getSuperclass()) { + extractTypeArguments(typeMap, instanceClass); + instanceClass = instanceClass.getSuperclass(); + if (instanceClass == null) { + return null; + } + } + + ParameterizedType parameterizedType = (ParameterizedType) instanceClass.getGenericSuperclass(); + Type actualType = parameterizedType.getActualTypeArguments()[parameterIndex]; + if (typeMap.containsKey(actualType)) { + actualType = typeMap.get(actualType); + } + if (actualType instanceof Class) { + return (Class) actualType; + } else if (actualType instanceof TypeVariable) { + return browseNestedTypes(instance, (TypeVariable) actualType); + } else { + return null; + } + } + + private static void extractTypeArguments(Map typeMap, Class clazz) { + Type genericSuperclass = clazz.getGenericSuperclass(); + if (!(genericSuperclass instanceof ParameterizedType)) { + return; + } + + ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; + Type[] typeParameter = ((Class) parameterizedType.getRawType()).getTypeParameters(); + Type[] actualTypeArgument = parameterizedType.getActualTypeArguments(); + for (int i = 0; i < typeParameter.length; i++) { + if (typeMap.containsKey(actualTypeArgument[i])) { + actualTypeArgument[i] = typeMap.get(actualTypeArgument[i]); + } + typeMap.put(typeParameter[i], actualTypeArgument[i]); + } + } + + private static Class browseNestedTypes(Object instance, TypeVariable actualType) { + Class instanceClass = instance.getClass(); + List> nestedOuterTypes = new LinkedList>(); + for (Class enclosingClass = instanceClass.getEnclosingClass(); + enclosingClass != null; + enclosingClass = enclosingClass.getEnclosingClass()) { + try { + Field this$0 = instanceClass.getDeclaredField("this$0"); + Object outerInstance = this$0.get(instance); + Class outerClass = outerInstance.getClass(); + nestedOuterTypes.add(outerClass); + Map outerTypeMap = new HashMap(); + extractTypeArguments(outerTypeMap, outerClass); + for (Map.Entry entry : outerTypeMap.entrySet()) { + if (!(entry.getKey() instanceof TypeVariable)) { + continue; + } + TypeVariable foundType = (TypeVariable) entry.getKey(); + if (foundType.getName().equals(actualType.getName()) + && isInnerClass(foundType.getGenericDeclaration(), actualType.getGenericDeclaration())) { + if (entry.getValue() instanceof Class) { + return (Class) entry.getValue(); + } + actualType = (TypeVariable) entry.getValue(); + } + } + } catch (NoSuchFieldException | IllegalAccessException e) { + + } + } + return null; + } + + private static boolean isInnerClass(GenericDeclaration outerDeclaration, GenericDeclaration innerDeclaration) { + if (!(outerDeclaration instanceof Class) || !(innerDeclaration instanceof Class)) { + return false; + } + Class outerClass = (Class) outerDeclaration; + Class innerClass = (Class) innerDeclaration; + while ((innerClass = innerClass.getEnclosingClass()) != null) { + if (innerClass == outerClass) { + return true; + } + } + return false; + } + + /* + * + * End of Generics Block + * + */ + + private static Field getField_Internal(final Class clazz, final String fieldName) throws NoSuchFieldException { + try { + Logger.REFLECTION("Field: Internal Lookup: " + fieldName); + Field k = clazz.getDeclaredField(fieldName); + makeFieldAccessible(k); + // Logger.REFLECTION("Got Field from Class. "+fieldName+" did exist within "+clazz.getCanonicalName()+"."); + return k; + } catch (final NoSuchFieldException e) { + Logger.REFLECTION("Field: Internal Lookup Failed: " + fieldName); + final Class superClass = clazz.getSuperclass(); + if (superClass == null) { + Logger.REFLECTION("Unable to find field '" + fieldName + "'"); + // Logger.REFLECTION("Failed to get Field from Class. "+fieldName+" does not existing within + // "+clazz.getCanonicalName()+"."); + throw e; + } + Logger.REFLECTION("Method: Recursion Lookup: " + fieldName + " - Checking in " + superClass.getName()); + // Logger.REFLECTION("Failed to get Field from Class. "+fieldName+" does not existing within + // "+clazz.getCanonicalName()+". Trying super class."); + return getField_Internal(superClass, fieldName); + } + } + + /** + * if (isPresent("com.optionaldependency.DependencyClass")) || + * This block will never execute when the dependency is not present. There is + * therefore no more risk of code throwing NoClassDefFoundException. + */ + private static boolean isClassPresent(final String className) { + try { + Class.forName(className); + return true; + } catch (final Throwable ex) { + // Class or one of its dependencies is not present... + return false; + } + } + + @Deprecated + public static Method getMethodViaReflection( + final Class lookupClass, final String methodName, final boolean invoke) throws Exception { + final Class lookup = lookupClass.getClass(); + final Method m = lookup.getDeclaredMethod(methodName); + m.setAccessible(true); // Abracadabra + if (invoke) { + m.invoke(lookup); // now its OK + } + return m; + } + + private static Method getMethod_Internal(Class aClass, String aMethodName, Class... aTypes) { + Method m = null; + try { + Logger.REFLECTION("Method: Internal Lookup: " + aMethodName); + m = aClass.getDeclaredMethod(aMethodName, aTypes); + if (m != null) { + m.setAccessible(true); + int modifiers = m.getModifiers(); + Field modifierField = m.getClass().getDeclaredField("modifiers"); + modifiers = modifiers & ~Modifier.FINAL; + modifierField.setAccessible(true); + modifierField.setInt(m, modifiers); + } + } catch (Throwable t) { + Logger.REFLECTION("Method: Internal Lookup Failed: " + aMethodName); + try { + m = getMethodRecursively(aClass, aMethodName); + } catch (NoSuchMethodException e) { + Logger.REFLECTION("Unable to find method '" + aMethodName + "'"); + e.printStackTrace(); + dumpClassInfo(aClass); + } + } + return m; + } + + private static Constructor getConstructor_Internal(Class aClass, Class... aTypes) { + Constructor c = null; + try { + Logger.REFLECTION("Constructor: Internal Lookup: " + aClass.getName()); + c = aClass.getDeclaredConstructor(aTypes); + if (c != null) { + c.setAccessible(true); + int modifiers = c.getModifiers(); + Field modifierField = c.getClass().getDeclaredField("modifiers"); + modifiers = modifiers & ~Modifier.FINAL; + modifierField.setAccessible(true); + modifierField.setInt(c, modifiers); + } + } catch (Throwable t) { + Logger.REFLECTION("Constructor: Internal Lookup Failed: " + aClass.getName()); + try { + c = getConstructorRecursively(aClass, aTypes); + } catch (Exception e) { + Logger.REFLECTION("Unable to find method '" + aClass.getName() + "'"); + e.printStackTrace(); + dumpClassInfo(aClass); + } + } + return c; + } + + private static Constructor getConstructorRecursively(Class aClass, Class... aTypes) throws Exception { + try { + Logger.REFLECTION("Constructor: Recursion Lookup: " + aClass.getName()); + Constructor c = aClass.getConstructor(aTypes); + if (c != null) { + c.setAccessible(true); + int modifiers = c.getModifiers(); + Field modifierField = c.getClass().getDeclaredField("modifiers"); + modifiers = modifiers & ~Modifier.FINAL; + modifierField.setAccessible(true); + modifierField.setInt(c, modifiers); + } + return c; + } catch (final NoSuchMethodException | IllegalArgumentException | IllegalAccessException e) { + final Class superClass = aClass.getSuperclass(); + if (superClass == null || superClass == Object.class) { + throw e; + } + return getConstructor_Internal(superClass, aTypes); + } + } + + private static Method getMethodRecursively(final Class clazz, final String aMethodName) + throws NoSuchMethodException { + try { + Logger.REFLECTION("Method: Recursion Lookup: " + aMethodName); + Method k = clazz.getDeclaredMethod(aMethodName); + makeMethodAccessible(k); + return k; + } catch (final NoSuchMethodException e) { + final Class superClass = clazz.getSuperclass(); + if (superClass == null || superClass == Object.class) { + throw e; + } + return getMethod_Internal(superClass, aMethodName); + } + } + + private static void dumpClassInfo(Class aClass) { + Logger.REFLECTION("We ran into an error processing reflection in " + aClass.getName() + + ", dumping all data for debugging."); + // Get the methods + Method[] methods = aClass.getDeclaredMethods(); + Field[] fields = aClass.getDeclaredFields(); + Constructor[] consts = aClass.getDeclaredConstructors(); + + Logger.REFLECTION("Dumping all Methods."); + for (Method method : methods) { + System.out.println(method.getName() + " | " + getDataStringFromArray(method.getParameterTypes())); + } + Logger.REFLECTION("Dumping all Fields."); + for (Field f : fields) { + System.out.println(f.getName()); + } + Logger.REFLECTION("Dumping all Constructors."); + for (Constructor c : consts) { + System.out.println(c.getName() + " | " + c.getParameterCount() + " | " + + getDataStringFromArray(c.getParameterTypes())); + } + } + + private static Class getNonPublicClass(final String className) { + Class c = null; + try { + c = Class.forName(className); + } catch (final ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // full package name --------^^^^^^^^^^ + // or simpler without Class.forName: + // Class c = package1.A.class; + + if (null != c) { + // In our case we need to use + Constructor constructor = null; + try { + constructor = c.getDeclaredConstructor(); + } catch (NoSuchMethodException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // note: getConstructor() can return only public constructors + // so we needed to search for any Declared constructor + + // now we need to make this constructor accessible + if (null != constructor) { + constructor.setAccessible(true); // ABRACADABRA! + + try { + final Object o = constructor.newInstance(); + return (Class) o; + } catch (InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + return null; + } + + private static Class getClass_Internal(String string) { + Class aClass = null; + if (ReflectionUtils.doesClassExist(string)) { + try { + aClass = Class.forName(string); + } catch (ClassNotFoundException e) { + aClass = getNonPublicClass(string); + } + } + + if (aClass == null) { + String aClassName = ""; + Logger.REFLECTION("Splitting " + string + " to try look for hidden classes."); + String[] aData = string.split("\\."); + Logger.REFLECTION("Obtained " + aData.length + " pieces."); + for (int i = 0; i < (aData.length - 1); i++) { + aClassName += (i > 0) ? "." + aData[i] : "" + aData[i]; + Logger.REFLECTION("Building: " + aClassName); + } + Logger.REFLECTION("Trying to search '" + aClassName + "' for inner classes."); + Class clazz = ReflectionUtils.getClass(aClassName); + + Class[] y = clazz.getDeclaredClasses(); + if (y == null || y.length <= 0) { + Logger.REFLECTION("No hidden inner classes found."); + return null; + } else { + boolean found = false; + for (Class h : y) { + Logger.REFLECTION("Found hidden inner class: " + h.getCanonicalName()); + if (h.getSimpleName().toLowerCase().equals(aData[aData.length - 1].toLowerCase())) { + Logger.REFLECTION("Found correct class. [" + aData[aData.length - 1] + + "] Caching at correct location: " + string); + Logger.REFLECTION("Found at location: " + h.getCanonicalName()); + ReflectionUtils.mCachedClasses.put(string, h); + aClass = h; + found = true; + break; + } + } + if (!found) { + return null; + } + } + } + return aClass; + } + + /** + * + * Set the value of a field reflectively. + */ + private static void setFieldValue_Internal(Object owner, Field field, Object value) throws Exception { + makeModifiable(field); + field.set(owner, value); + } + + /** + * Force the field to be modifiable and accessible. + */ + private static void makeModifiable(Field nameField) throws Exception { + nameField.setAccessible(true); + int modifiers = nameField.getModifiers(); + Field modifierField = nameField.getClass().getDeclaredField("modifiers"); + modifiers = modifiers & ~Modifier.FINAL; + modifierField.setAccessible(true); + modifierField.setInt(nameField, modifiers); + } + + public static boolean doesFieldExist(String clazz, String string) { + return doesFieldExist(ReflectionUtils.getClass(clazz), string); + } + + public static boolean doesFieldExist(Class clazz, String string) { + if (clazz != null) { + if (ReflectionUtils.getField(clazz, string) != null) { + return true; + } + } + return false; + } + + public static Object getFieldValue(Field field) { + return getFieldValue(field, null); + } + + public static Object getFieldValue(Field field, Object instance) { + try { + return field.get(instance); + } catch (IllegalArgumentException | IllegalAccessException e) { + } + return null; + } + + private static final String getDataStringFromArray(V[] parameterTypes) { + if (parameterTypes == null || parameterTypes.length == 0) { + return "empty/null"; + } else { + String aData = ""; + for (V y : parameterTypes) { + if (y != null) { + aData += ", " + y.toString(); + } + } + return aData; + } + } } diff --git a/src/main/java/alkalus/main/core/util/TooltipHandler.java b/src/main/java/alkalus/main/core/util/TooltipHandler.java index 072726b..5e114bb 100644 --- a/src/main/java/alkalus/main/core/util/TooltipHandler.java +++ b/src/main/java/alkalus/main/core/util/TooltipHandler.java @@ -10,52 +10,49 @@ public class TooltipHandler { - private static Item mPoppetShelfItem; - private static Block mPoppetShelfBlock; - private static ItemStack mPoppetShelfStack; - private static final Class mPoppetShelfClass; - - static { - mPoppetShelfClass = ReflectionUtils.getClass("com.emoniph.witchery.blocks.BlockPoppetShelf"); - } + private static Item mPoppetShelfItem; + private static Block mPoppetShelfBlock; + private static ItemStack mPoppetShelfStack; + private static final Class mPoppetShelfClass; - @SubscribeEvent - public void onItemTooltip(ItemTooltipEvent event){ - - if (mPoppetShelfBlock == null || mPoppetShelfItem == null || mPoppetShelfStack == null) { - if (event.itemStack != null && event.itemStack.getItem() != null) { - // Set Block - if (mPoppetShelfBlock == null) { - Block b = Block.getBlockFromItem(event.itemStack.getItem()); - if (mPoppetShelfClass.isInstance(b)) { - mPoppetShelfBlock = b; - } - } - if (mPoppetShelfItem == null || mPoppetShelfStack == null) { - // Set Item/ItemStack from Block since it matches. - if (mPoppetShelfBlock != null) { - Item i = Item.getItemFromBlock(mPoppetShelfBlock); - if (i != null) { - mPoppetShelfItem = i; - mPoppetShelfStack = new ItemStack(mPoppetShelfItem); - } - } - } - } - } - - // Variables are set Ok, now to add a tooltip. - if (mPoppetShelfStack != null) { - if (Utils.areStacksEqual(mPoppetShelfStack, event.itemStack, true)) { - if (!AsmConfig.allowPoppetShelfChunkLoading) { - event.toolTip.add(EnumChatFormatting.RED+"This block has chunkloading disabled"); - } - else { - event.toolTip.add(EnumChatFormatting.GREEN+"This block has chunkloading enabled"); - } - } - } - - - } + static { + mPoppetShelfClass = ReflectionUtils.getClass("com.emoniph.witchery.blocks.BlockPoppetShelf"); + } + + @SubscribeEvent + public void onItemTooltip(ItemTooltipEvent event) { + + if (mPoppetShelfBlock == null || mPoppetShelfItem == null || mPoppetShelfStack == null) { + if (event.itemStack != null && event.itemStack.getItem() != null) { + // Set Block + if (mPoppetShelfBlock == null) { + Block b = Block.getBlockFromItem(event.itemStack.getItem()); + if (mPoppetShelfClass.isInstance(b)) { + mPoppetShelfBlock = b; + } + } + if (mPoppetShelfItem == null || mPoppetShelfStack == null) { + // Set Item/ItemStack from Block since it matches. + if (mPoppetShelfBlock != null) { + Item i = Item.getItemFromBlock(mPoppetShelfBlock); + if (i != null) { + mPoppetShelfItem = i; + mPoppetShelfStack = new ItemStack(mPoppetShelfItem); + } + } + } + } + } + + // Variables are set Ok, now to add a tooltip. + if (mPoppetShelfStack != null) { + if (Utils.areStacksEqual(mPoppetShelfStack, event.itemStack, true)) { + if (!AsmConfig.allowPoppetShelfChunkLoading) { + event.toolTip.add(EnumChatFormatting.RED + "This block has chunkloading disabled"); + } else { + event.toolTip.add(EnumChatFormatting.GREEN + "This block has chunkloading enabled"); + } + } + } + } } diff --git a/src/main/java/alkalus/main/core/util/Utils.java b/src/main/java/alkalus/main/core/util/Utils.java index ab7f1e0..16980ca 100644 --- a/src/main/java/alkalus/main/core/util/Utils.java +++ b/src/main/java/alkalus/main/core/util/Utils.java @@ -1,9 +1,8 @@ package alkalus.main.core.util; +import cpw.mods.fml.common.FMLCommonHandler; import java.util.HashSet; import java.util.List; - -import cpw.mods.fml.common.FMLCommonHandler; import net.minecraft.block.Block; import net.minecraft.init.Items; import net.minecraft.item.Item; @@ -21,111 +20,118 @@ public class Utils { */ public static final short W = OreDictionary.WILDCARD_VALUE; - public synchronized static ItemStack getSimpleStack(final Item x, final int i){ - return getSimpleStack(new ItemStack(x), i); - } - - public synchronized static ItemStack getSimpleStack(final ItemStack x, final int i){ - try { - final ItemStack r = x.copy(); - r.stackSize = i; - return r; - } catch(final Throwable e){ - return null; - } - } - - public static ItemStack[] getAllItemsFromOreDictEntry(String oreDictName) { - return getAllItemsFromOreDictEntry(oreDictName, new ItemStack[] {}); - } - - public static ItemStack[] getAllItemsFromOreDictEntry(String oreDictName, ItemStack[] exclusions) { - HashSet Q = new HashSet(); - if (OreDictionary.doesOreNameExist(oreDictName)) { - for (ItemStack i : OreDictionary.getOres(oreDictName)) { - if ( i != null) { - if (exclusions.length > 0) { - for (int r=0;r 0) { - V = new ItemStack[Q.size()]; - for (ItemStack w : Q) { - V[mSlot++] = w; - } - } - return V; - } - - @SuppressWarnings("unchecked") - public static synchronized boolean removeAllCraftingRecipesByOutputItem(final ItemStack I){ - if (I == null) { - return false; - } - List recipes = CraftingManager.getInstance().getRecipeList(); - return recipes.removeIf(s -> (s != null) && (s.getRecipeOutput() != null) && (s.getRecipeOutput().isItemEqual(I))); - } - - public static void registerEvent(Object o){ - MinecraftForge.EVENT_BUS.register(o); - FMLCommonHandler.instance().bus().register(o); - } - - public static boolean hasValidOreDictTag(String validTag, ItemStack hasTag) { - if (hasTag != null) { - for(int tag: OreDictionary.getOreIDs(hasTag)) { - String oreName = OreDictionary.getOreName(tag); - if (oreName.equalsIgnoreCase(validTag)) { - return true; - } - - } - } - return false; - } - - public static ItemStack simpleMetaStack(final Item item, final int meta, final int size){ - try { - if (item == null){ - return null; - } - final ItemStack metaStack = new ItemStack(item,size,meta); - return metaStack; - - } catch (final NullPointerException e) { - return null; - } - } - - public static ItemStack simpleMetaStack(final Block block, final int meta, final int size) { - return simpleMetaStack(Item.getItemFromBlock(block), meta, size); - } + public static synchronized ItemStack getSimpleStack(final Item x, final int i) { + return getSimpleStack(new ItemStack(x), i); + } + + public static synchronized ItemStack getSimpleStack(final ItemStack x, final int i) { + try { + final ItemStack r = x.copy(); + r.stackSize = i; + return r; + } catch (final Throwable e) { + return null; + } + } + + public static ItemStack[] getAllItemsFromOreDictEntry(String oreDictName) { + return getAllItemsFromOreDictEntry(oreDictName, new ItemStack[] {}); + } + + public static ItemStack[] getAllItemsFromOreDictEntry(String oreDictName, ItemStack[] exclusions) { + HashSet Q = new HashSet(); + if (OreDictionary.doesOreNameExist(oreDictName)) { + for (ItemStack i : OreDictionary.getOres(oreDictName)) { + if (i != null) { + if (exclusions.length > 0) { + for (int r = 0; r < exclusions.length; r++) { + if (!i.equals(exclusions[r]) && !ItemStack.areItemStacksEqual(i, exclusions[r])) { + Q.add(i); + } else { + continue; + } + } + } else { + Q.add(i); + } + } + } + } + + ItemStack[] V = new ItemStack[] {}; + int mSlot = 0; + if (Q.size() > 0) { + V = new ItemStack[Q.size()]; + for (ItemStack w : Q) { + V[mSlot++] = w; + } + } + return V; + } + + @SuppressWarnings("unchecked") + public static synchronized boolean removeAllCraftingRecipesByOutputItem(final ItemStack I) { + if (I == null) { + return false; + } + List recipes = CraftingManager.getInstance().getRecipeList(); + return recipes.removeIf(s -> (s != null) + && (s.getRecipeOutput() != null) + && (s.getRecipeOutput().isItemEqual(I))); + } + + public static void registerEvent(Object o) { + MinecraftForge.EVENT_BUS.register(o); + FMLCommonHandler.instance().bus().register(o); + } + + public static boolean hasValidOreDictTag(String validTag, ItemStack hasTag) { + if (hasTag != null) { + for (int tag : OreDictionary.getOreIDs(hasTag)) { + String oreName = OreDictionary.getOreName(tag); + if (oreName.equalsIgnoreCase(validTag)) { + return true; + } + } + } + return false; + } + + public static ItemStack simpleMetaStack(final Item item, final int meta, final int size) { + try { + if (item == null) { + return null; + } + final ItemStack metaStack = new ItemStack(item, size, meta); + return metaStack; + + } catch (final NullPointerException e) { + return null; + } + } + + public static ItemStack simpleMetaStack(final Block block, final int meta, final int size) { + return simpleMetaStack(Item.getItemFromBlock(block), meta, size); + } public static boolean areStacksEqual(ItemStack aStack1, ItemStack aStack2) { return areStacksEqual(aStack1, aStack2, false); } public static boolean areStacksEqual(ItemStack aStack1, ItemStack aStack2, boolean aIgnoreNBT) { - return aStack1 != null && aStack2 != null && aStack1.getItem() == aStack2.getItem() && (aIgnoreNBT || ((aStack1.getTagCompound() == null) == (aStack2.getTagCompound() == null)) && (aStack1.getTagCompound() == null || aStack1.getTagCompound().equals(aStack2.getTagCompound()))) && (Items.feather.getDamage(aStack1) == Items.feather.getDamage(aStack2) || Items.feather.getDamage(aStack1) == W || Items.feather.getDamage(aStack2) == W); + return aStack1 != null + && aStack2 != null + && aStack1.getItem() == aStack2.getItem() + && (aIgnoreNBT + || ((aStack1.getTagCompound() == null) == (aStack2.getTagCompound() == null)) + && (aStack1.getTagCompound() == null + || aStack1.getTagCompound().equals(aStack2.getTagCompound()))) + && (Items.feather.getDamage(aStack1) == Items.feather.getDamage(aStack2) + || Items.feather.getDamage(aStack1) == W + || Items.feather.getDamage(aStack2) == W); } - public static boolean isDevEnv() { - return (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment"); - } - + public static boolean isDevEnv() { + return (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment"); + } } diff --git a/src/main/java/alkalus/main/core/util/WitcheryRecipeHandlerInternal.java b/src/main/java/alkalus/main/core/util/WitcheryRecipeHandlerInternal.java index bf96e8b..d8b4832 100644 --- a/src/main/java/alkalus/main/core/util/WitcheryRecipeHandlerInternal.java +++ b/src/main/java/alkalus/main/core/util/WitcheryRecipeHandlerInternal.java @@ -1,10 +1,17 @@ package alkalus.main.core.util; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Hashtable; - +import alkalus.main.core.WitcheryExtras; +import alkalus.main.core.crafting.OvenRecipes; +import alkalus.main.core.crafting.OvenRecipes.OvenRecipe; +import alkalus.main.core.types.Witchery_Cauldron; +import alkalus.main.core.types.Witchery_CreaturePower; +import alkalus.main.core.types.Witchery_Distillery; +import alkalus.main.core.types.Witchery_Infusion; +import alkalus.main.core.types.Witchery_Kettle; +import alkalus.main.core.types.Witchery_Oven; +import alkalus.main.core.types.Witchery_Predictions; +import alkalus.main.core.types.Witchery_Rite; +import alkalus.main.core.types.Witchery_SpinningWheel; import com.emoniph.witchery.crafting.DistilleryRecipes; import com.emoniph.witchery.crafting.DistilleryRecipes.DistilleryRecipe; import com.emoniph.witchery.crafting.KettleRecipes; @@ -21,353 +28,377 @@ import com.emoniph.witchery.ritual.RiteRegistry.Ritual; import com.emoniph.witchery.ritual.RitualTraits; import com.emoniph.witchery.ritual.Sacrifice; - -import alkalus.main.core.WitcheryExtras; -import alkalus.main.core.crafting.OvenRecipes; -import alkalus.main.core.crafting.OvenRecipes.OvenRecipe; -import alkalus.main.core.types.Witchery_Cauldron; -import alkalus.main.core.types.Witchery_CreaturePower; -import alkalus.main.core.types.Witchery_Distillery; -import alkalus.main.core.types.Witchery_Infusion; -import alkalus.main.core.types.Witchery_Kettle; -import alkalus.main.core.types.Witchery_Oven; -import alkalus.main.core.types.Witchery_Predictions; -import alkalus.main.core.types.Witchery_Rite; -import alkalus.main.core.types.Witchery_SpinningWheel; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Hashtable; import net.minecraft.item.ItemStack; public class WitcheryRecipeHandlerInternal { - public static final Witchery_Cauldron mCauldronHandler = new Witchery_Cauldron(); - public static final Witchery_CreaturePower mCreaturePowerHandler = new Witchery_CreaturePower(); - public static final Witchery_Distillery mDistilleryHandler = new Witchery_Distillery(); - public static final Witchery_Infusion mInfusionHandler = new Witchery_Infusion(); - public static final Witchery_Kettle mKettleHandler = new Witchery_Kettle(); - public static final Witchery_Oven mOvenHandler = new Witchery_Oven(); - public static final Witchery_Predictions mPredictionsHandler = new Witchery_Predictions(); - public static final Witchery_Rite mRitesHandler = new Witchery_Rite(); - public static final Witchery_SpinningWheel mSpinningWheelHandler = new Witchery_SpinningWheel(); - - - - /* - * Oven Recipes - */ - public static synchronized boolean addOvenRecipe(final ItemStack input1, final String inputString1, final int jars, final ItemStack customOutput, final int amt1, final ItemStack outputJarStack, final int amt2) { - if (OvenRecipes.addRecipe(input1, inputString1, jars, customOutput, amt1, outputJarStack, amt2) != null) { - return true; - } - return false; - } - - public static synchronized boolean removeOvenRecipe(OvenRecipe mRecipe) { - if (mRecipe == null) { - WitcheryExtras.log(2, "Null Oven Recipe parsed into removeOvenRecipe(). Please check all OvenRecipes are valid before calling this function."); - return false; - } - boolean aDidRemove = false; - ArrayList aRecipes = OvenRecipes.getRecipeMap(); - if (aRecipes.contains(mRecipe)) { - if (aRecipes.remove(mRecipe)) { - aDidRemove = true; - } - } - if (aDidRemove) { - WitcheryExtras.log(0, "Removed Oven recipe: "+mRecipe.getDescription()); - } - else { - WitcheryExtras.log(0, "Failed to remove Oven recipe: "+mRecipe.getDescription()); - } - return aDidRemove; - } - - - - - /* - * Distillery Recipes - */ - - public static synchronized boolean addDistilleryRecipe(ItemStack input1, ItemStack input2, int jars, ItemStack output1, ItemStack output2, ItemStack output3, ItemStack output4) { - if (DistilleryRecipes.instance().addRecipe(input1, input2, jars, output1, output2, output3, output4) != null) { - return true; - } - return false; - } - - public static synchronized boolean removeDistilleryRecipe(DistilleryRecipe mRecipe) { - if (mRecipe == null) { - WitcheryExtras.log(2, "Null Distillery Recipe parsed into removeDistilleryRecipe(). Please check all DistilleryRecipes are valid before calling this function."); - return false; - } - boolean aDidRemove = false; - if (DistilleryRecipes.instance().recipes.contains(mRecipe)) { - if (DistilleryRecipes.instance().recipes.remove(mRecipe)) { - aDidRemove = true; - } - } - if (aDidRemove) { - WitcheryExtras.log(0, "Removed Distillery recipe: "+mRecipe.getDescription()); - } - else { - WitcheryExtras.log(0, "Failed to remove Distillery recipe: "+mRecipe.getDescription()); - } - return aDidRemove; - } - - - - - - - - /* - * Kettle Recipes - */ - - public static synchronized boolean addKettleRecipe(ItemStack output, int hatBonus, int familiarType, float powerRequired, int color, int dimension, boolean inBook, ItemStack... inputs) { - if (KettleRecipes.instance().addRecipe(output, hatBonus, familiarType, powerRequired, color, dimension, inBook, inputs) != null) { - return true; - } - return false; - } - - public static synchronized boolean removeKettleRecipe(ItemStack mOutput) { - KettleRecipe toRemove = KettleRecipes.instance().findRecipeFor(mOutput); - if (mOutput == null || toRemove == null) { - WitcheryExtras.log(2, "Null Kettle Recipe parsed into removeKettleRecipe(). Please check all ItemStacks are valid before calling this function."); - return false; - } - boolean aDidRemove = false; - if (KettleRecipes.instance().recipes.contains(toRemove)) { - if (KettleRecipes.instance().recipes.remove(toRemove)) { - aDidRemove = true; - } - } - if (aDidRemove) { - WitcheryExtras.log(0, "Removed Kettle recipe for output: "+toRemove.output.getDisplayName()+". "+toRemove.getDescription()); - } - else { - WitcheryExtras.log(0, "Failed to remove Kettle recipe for "+mOutput.getDisplayName()); - } - return aDidRemove; - } - - - - - - - - /* - * Creature Powers - */ - - public static synchronized boolean addNewCreaturePower(CreaturePower power) { - try { - CreaturePower.Registry.instance().add(power); - return true; - } - catch (NullPointerException e) { - return false; - } - } - - - @SuppressWarnings("unchecked") - public static synchronized boolean removeCreaturePower(CreaturePower power) { - Field aRegistry = ReflectionUtils.getField(CreaturePower.Registry.class, "registry"); - if (power == null || aRegistry == null || ReflectionUtils.getFieldValue(aRegistry, CreaturePower.Registry.instance()) != null) { - WitcheryExtras.log(2, "Null CreaturePower parsed into removeCreaturePower(). Please check all CreaturePowers are valid before calling this function."); - return false; - } - ArrayList registry = (ArrayList) ReflectionUtils.getFieldValue(aRegistry, CreaturePower.Registry.instance()); - int aSizeStart = registry.size(); - for (CreaturePower aCreaturePower : registry) { - if (aCreaturePower != null && aCreaturePower.getCreaturePowerID() == power.getCreaturePowerID()) { - registry.remove(aCreaturePower); - WitcheryExtras.log(0, "Removed CreaturePower: "+aCreaturePower.getCreaturePowerID()+"."); - break; - } - } - if (registry.size() >= aSizeStart) { - WitcheryExtras.log(0, "Failed to remove CreaturePower: "+power.getCreaturePowerID()+"."); - } - return registry.size() < aSizeStart; - } - - - - - - - - /* - * Rites - */ - - public static synchronized boolean addNewRiteToRiteRegistry(int ritualID, int bookIndex, Rite rite, Sacrifice initialSacrifice, EnumSet traits, Circle... circles) { - if (ritualID > Byte.MAX_VALUE) { - WitcheryExtras.log(1, "RitualID for Rite: "+rite.toString()+" has an ID greater than "+Byte.MAX_VALUE+". Found ID: "+ritualID+"."); - return false; - } - if (RiteRegistry.addRecipe((byte)ritualID, bookIndex, rite, initialSacrifice, traits, circles) != null) { - return true; - } - return false; - } - - public static synchronized boolean removeRiteFromRiteRegistry(int ritualID) { - if (ritualID < Byte.MIN_VALUE || ritualID > Byte.MAX_VALUE) { - WitcheryExtras.log(2, "Failed to remove Rite, ID exceeded range of a byte. Found: "+ritualID+", Expected: "+Byte.MIN_VALUE+"-"+Byte.MAX_VALUE+"."); - return false; - } - Ritual toRemove = RiteRegistry.instance().getRitual((byte) ritualID); - if (toRemove == null) { - WitcheryExtras.log(2, "Invalid Rite ID parsed into removeRiteFromRiteRegistry(int). Please check ID is mapped before calling this function."); - return false; - } - boolean aDidRemove = false; - if (RiteRegistry.instance().getRituals().contains(toRemove)) { - if (RiteRegistry.instance().getRituals().remove(toRemove)) { - aDidRemove = true; - } - } - if (aDidRemove) { - WitcheryExtras.log(0, "Removed Rite: "+toRemove.getDescription()); - } - else { - WitcheryExtras.log(0, "Failed to remove Rite: "+(toRemove != null ? toRemove.getLocalizedName()+" | "+toRemove.getRitualID()+" | "+toRemove.getDescription() : ritualID)); - } - return aDidRemove; - } - - - - - - - - /* - * Predictions - */ - - public static synchronized boolean addNewPrediction(Prediction prediction) { - try { - PredictionManager.instance().addPrediction(prediction); - WitcheryExtras.log(0, "Added Prediction: "+prediction.getTranslationKey()+" | "+prediction.predictionID); - return true; - } - catch (NullPointerException e) { - return false; - } - } - - public static synchronized boolean removePrediction(Prediction prediction) { - Field aRegistry = ReflectionUtils.getField(PredictionManager.class, "predictions"); - if (prediction == null) { - WitcheryExtras.log(2, "Null Prediction parsed into removePrediction(). Please check all Predictions are valid before calling this function."); - return false; - } - PredictionManager aInstance = PredictionManager.instance(); - Hashtable predictions = (Hashtable) ReflectionUtils.getFieldValue(aRegistry, aInstance); - int aSizeStart = predictions.size(); - for (Prediction aPredic : predictions.values()) { - if (aPredic != null && aPredic.predictionID == prediction.predictionID) { - predictions.remove(prediction.predictionID); - WitcheryExtras.log(0, "Removed Prediction: "+aPredic.getTranslationKey()+" | "+aPredic.predictionID); - break; - } - } - if (predictions.size() >= aSizeStart) { - WitcheryExtras.log(0, "Failed to remove Prediction: "+(prediction != null ? prediction.getTranslationKey()+", "+prediction.predictionID : prediction.predictionID)); - } - return predictions.size() < aSizeStart; - } - - - - - - - - /* - * Infusion Recipes - */ - - public static synchronized boolean addNewInfusion(Infusion infusion) { - try { - Infusion.Registry.instance().add(infusion); - return true; - } - catch (NullPointerException e) { - return false; - } - } - - public static synchronized boolean removeInfusion(Infusion infusion) { - if (infusion == null) { - WitcheryExtras.log(2, "Null Infusion parsed into removeInfusion(). Please check all Infusions are valid before calling this function."); - return false; - } - Field aRegistry = ReflectionUtils.getField(CreaturePower.Registry.class, "registry"); - if (infusion == null || aRegistry == null || ReflectionUtils.getFieldValue(aRegistry, Infusion.Registry.instance()) != null) { - WitcheryExtras.log(2, "Null Infusion parsed into removeInfusion(). Please check all Infusions are valid before calling this function."); - return false; - } - ArrayList infusions = (ArrayList) ReflectionUtils.getFieldValue(aRegistry, Infusion.Registry.instance()); - int aSizeStart = infusions.size(); - for (Infusion aInfusion : infusions) { - if (aInfusion != null && aInfusion.infusionID == infusion.infusionID) { - infusions.remove(aInfusion); - WitcheryExtras.log(0, "Removed Infusion: "+infusion.toString()+" | "+infusion.infusionID); - break; - } - } - if (infusions.size() >= aSizeStart) { - WitcheryExtras.log(1, "Failed to remove Infusion: "+(infusion != null ? infusion.toString()+" | "+infusion.infusionID+" | " : infusion.infusionID)); - } - return infusions.size() < aSizeStart; - } - - - - - - - - /* - * Spinning Recipes - */ - - public static synchronized boolean addSpinningWheelRecipe(ItemStack result, ItemStack fibre, ItemStack... modifiers) { - if (result == null || fibre == null) { - return false; - } - SpinningRecipes.instance().addRecipe(result, fibre, modifiers); - return true; - } - - public static boolean removeSpinningWheelRecipe(ItemStack result, ItemStack fibre, ItemStack... modifiers) { - SpinningRecipe aRecipeToRemove = null; - for (SpinningRecipe aRecipe : SpinningRecipes.instance().recipes) { - if (Utils.areStacksEqual(fibre, aRecipe.fibre)) { - if (Utils.areStacksEqual(result, aRecipe.result)) { - if (modifiers.length > 0 && aRecipe.modifiers.length > 0 && modifiers.length == aRecipe.modifiers.length) { - aRecipeToRemove = aRecipe; - break; - } - } - } - } - if (aRecipeToRemove != null) { - return SpinningRecipes.instance().recipes.remove(aRecipeToRemove); - } - return false; - } - - public static boolean removeSpinningRecipe(SpinningRecipe mRecipe) { - return removeSpinningWheelRecipe(mRecipe.result, mRecipe.fibre, mRecipe.modifiers); - } - + public static final Witchery_Cauldron mCauldronHandler = new Witchery_Cauldron(); + public static final Witchery_CreaturePower mCreaturePowerHandler = new Witchery_CreaturePower(); + public static final Witchery_Distillery mDistilleryHandler = new Witchery_Distillery(); + public static final Witchery_Infusion mInfusionHandler = new Witchery_Infusion(); + public static final Witchery_Kettle mKettleHandler = new Witchery_Kettle(); + public static final Witchery_Oven mOvenHandler = new Witchery_Oven(); + public static final Witchery_Predictions mPredictionsHandler = new Witchery_Predictions(); + public static final Witchery_Rite mRitesHandler = new Witchery_Rite(); + public static final Witchery_SpinningWheel mSpinningWheelHandler = new Witchery_SpinningWheel(); + + /* + * Oven Recipes + */ + public static synchronized boolean addOvenRecipe( + final ItemStack input1, + final String inputString1, + final int jars, + final ItemStack customOutput, + final int amt1, + final ItemStack outputJarStack, + final int amt2) { + if (OvenRecipes.addRecipe(input1, inputString1, jars, customOutput, amt1, outputJarStack, amt2) != null) { + return true; + } + return false; + } + + public static synchronized boolean removeOvenRecipe(OvenRecipe mRecipe) { + if (mRecipe == null) { + WitcheryExtras.log( + 2, + "Null Oven Recipe parsed into removeOvenRecipe(). Please check all OvenRecipes are valid before calling this function."); + return false; + } + boolean aDidRemove = false; + ArrayList aRecipes = OvenRecipes.getRecipeMap(); + if (aRecipes.contains(mRecipe)) { + if (aRecipes.remove(mRecipe)) { + aDidRemove = true; + } + } + if (aDidRemove) { + WitcheryExtras.log(0, "Removed Oven recipe: " + mRecipe.getDescription()); + } else { + WitcheryExtras.log(0, "Failed to remove Oven recipe: " + mRecipe.getDescription()); + } + return aDidRemove; + } + + /* + * Distillery Recipes + */ + + public static synchronized boolean addDistilleryRecipe( + ItemStack input1, + ItemStack input2, + int jars, + ItemStack output1, + ItemStack output2, + ItemStack output3, + ItemStack output4) { + if (DistilleryRecipes.instance().addRecipe(input1, input2, jars, output1, output2, output3, output4) != null) { + return true; + } + return false; + } + + public static synchronized boolean removeDistilleryRecipe(DistilleryRecipe mRecipe) { + if (mRecipe == null) { + WitcheryExtras.log( + 2, + "Null Distillery Recipe parsed into removeDistilleryRecipe(). Please check all DistilleryRecipes are valid before calling this function."); + return false; + } + boolean aDidRemove = false; + if (DistilleryRecipes.instance().recipes.contains(mRecipe)) { + if (DistilleryRecipes.instance().recipes.remove(mRecipe)) { + aDidRemove = true; + } + } + if (aDidRemove) { + WitcheryExtras.log(0, "Removed Distillery recipe: " + mRecipe.getDescription()); + } else { + WitcheryExtras.log(0, "Failed to remove Distillery recipe: " + mRecipe.getDescription()); + } + return aDidRemove; + } + + /* + * Kettle Recipes + */ + + public static synchronized boolean addKettleRecipe( + ItemStack output, + int hatBonus, + int familiarType, + float powerRequired, + int color, + int dimension, + boolean inBook, + ItemStack... inputs) { + if (KettleRecipes.instance() + .addRecipe(output, hatBonus, familiarType, powerRequired, color, dimension, inBook, inputs) + != null) { + return true; + } + return false; + } + + public static synchronized boolean removeKettleRecipe(ItemStack mOutput) { + KettleRecipe toRemove = KettleRecipes.instance().findRecipeFor(mOutput); + if (mOutput == null || toRemove == null) { + WitcheryExtras.log( + 2, + "Null Kettle Recipe parsed into removeKettleRecipe(). Please check all ItemStacks are valid before calling this function."); + return false; + } + boolean aDidRemove = false; + if (KettleRecipes.instance().recipes.contains(toRemove)) { + if (KettleRecipes.instance().recipes.remove(toRemove)) { + aDidRemove = true; + } + } + if (aDidRemove) { + WitcheryExtras.log( + 0, + "Removed Kettle recipe for output: " + toRemove.output.getDisplayName() + ". " + + toRemove.getDescription()); + } else { + WitcheryExtras.log(0, "Failed to remove Kettle recipe for " + mOutput.getDisplayName()); + } + return aDidRemove; + } + + /* + * Creature Powers + */ + + public static synchronized boolean addNewCreaturePower(CreaturePower power) { + try { + CreaturePower.Registry.instance().add(power); + return true; + } catch (NullPointerException e) { + return false; + } + } + + @SuppressWarnings("unchecked") + public static synchronized boolean removeCreaturePower(CreaturePower power) { + Field aRegistry = ReflectionUtils.getField(CreaturePower.Registry.class, "registry"); + if (power == null + || aRegistry == null + || ReflectionUtils.getFieldValue(aRegistry, CreaturePower.Registry.instance()) != null) { + WitcheryExtras.log( + 2, + "Null CreaturePower parsed into removeCreaturePower(). Please check all CreaturePowers are valid before calling this function."); + return false; + } + ArrayList registry = + (ArrayList) ReflectionUtils.getFieldValue(aRegistry, CreaturePower.Registry.instance()); + int aSizeStart = registry.size(); + for (CreaturePower aCreaturePower : registry) { + if (aCreaturePower != null && aCreaturePower.getCreaturePowerID() == power.getCreaturePowerID()) { + registry.remove(aCreaturePower); + WitcheryExtras.log(0, "Removed CreaturePower: " + aCreaturePower.getCreaturePowerID() + "."); + break; + } + } + if (registry.size() >= aSizeStart) { + WitcheryExtras.log(0, "Failed to remove CreaturePower: " + power.getCreaturePowerID() + "."); + } + return registry.size() < aSizeStart; + } + + /* + * Rites + */ + + public static synchronized boolean addNewRiteToRiteRegistry( + int ritualID, + int bookIndex, + Rite rite, + Sacrifice initialSacrifice, + EnumSet traits, + Circle... circles) { + if (ritualID > Byte.MAX_VALUE) { + WitcheryExtras.log( + 1, + "RitualID for Rite: " + rite.toString() + " has an ID greater than " + Byte.MAX_VALUE + + ". Found ID: " + ritualID + "."); + return false; + } + if (RiteRegistry.addRecipe((byte) ritualID, bookIndex, rite, initialSacrifice, traits, circles) != null) { + return true; + } + return false; + } + + public static synchronized boolean removeRiteFromRiteRegistry(int ritualID) { + if (ritualID < Byte.MIN_VALUE || ritualID > Byte.MAX_VALUE) { + WitcheryExtras.log( + 2, + "Failed to remove Rite, ID exceeded range of a byte. Found: " + ritualID + ", Expected: " + + Byte.MIN_VALUE + "-" + Byte.MAX_VALUE + "."); + return false; + } + Ritual toRemove = RiteRegistry.instance().getRitual((byte) ritualID); + if (toRemove == null) { + WitcheryExtras.log( + 2, + "Invalid Rite ID parsed into removeRiteFromRiteRegistry(int). Please check ID is mapped before calling this function."); + return false; + } + boolean aDidRemove = false; + if (RiteRegistry.instance().getRituals().contains(toRemove)) { + if (RiteRegistry.instance().getRituals().remove(toRemove)) { + aDidRemove = true; + } + } + if (aDidRemove) { + WitcheryExtras.log(0, "Removed Rite: " + toRemove.getDescription()); + } else { + WitcheryExtras.log( + 0, + "Failed to remove Rite: " + + (toRemove != null + ? toRemove.getLocalizedName() + " | " + toRemove.getRitualID() + " | " + + toRemove.getDescription() + : ritualID)); + } + return aDidRemove; + } + + /* + * Predictions + */ + + public static synchronized boolean addNewPrediction(Prediction prediction) { + try { + PredictionManager.instance().addPrediction(prediction); + WitcheryExtras.log( + 0, "Added Prediction: " + prediction.getTranslationKey() + " | " + prediction.predictionID); + return true; + } catch (NullPointerException e) { + return false; + } + } + + public static synchronized boolean removePrediction(Prediction prediction) { + Field aRegistry = ReflectionUtils.getField(PredictionManager.class, "predictions"); + if (prediction == null) { + WitcheryExtras.log( + 2, + "Null Prediction parsed into removePrediction(). Please check all Predictions are valid before calling this function."); + return false; + } + PredictionManager aInstance = PredictionManager.instance(); + Hashtable predictions = + (Hashtable) ReflectionUtils.getFieldValue(aRegistry, aInstance); + int aSizeStart = predictions.size(); + for (Prediction aPredic : predictions.values()) { + if (aPredic != null && aPredic.predictionID == prediction.predictionID) { + predictions.remove(prediction.predictionID); + WitcheryExtras.log( + 0, "Removed Prediction: " + aPredic.getTranslationKey() + " | " + aPredic.predictionID); + break; + } + } + if (predictions.size() >= aSizeStart) { + WitcheryExtras.log( + 0, + "Failed to remove Prediction: " + + (prediction != null + ? prediction.getTranslationKey() + ", " + prediction.predictionID + : prediction.predictionID)); + } + return predictions.size() < aSizeStart; + } + + /* + * Infusion Recipes + */ + + public static synchronized boolean addNewInfusion(Infusion infusion) { + try { + Infusion.Registry.instance().add(infusion); + return true; + } catch (NullPointerException e) { + return false; + } + } + + public static synchronized boolean removeInfusion(Infusion infusion) { + if (infusion == null) { + WitcheryExtras.log( + 2, + "Null Infusion parsed into removeInfusion(). Please check all Infusions are valid before calling this function."); + return false; + } + Field aRegistry = ReflectionUtils.getField(CreaturePower.Registry.class, "registry"); + if (infusion == null + || aRegistry == null + || ReflectionUtils.getFieldValue(aRegistry, Infusion.Registry.instance()) != null) { + WitcheryExtras.log( + 2, + "Null Infusion parsed into removeInfusion(). Please check all Infusions are valid before calling this function."); + return false; + } + ArrayList infusions = + (ArrayList) ReflectionUtils.getFieldValue(aRegistry, Infusion.Registry.instance()); + int aSizeStart = infusions.size(); + for (Infusion aInfusion : infusions) { + if (aInfusion != null && aInfusion.infusionID == infusion.infusionID) { + infusions.remove(aInfusion); + WitcheryExtras.log(0, "Removed Infusion: " + infusion.toString() + " | " + infusion.infusionID); + break; + } + } + if (infusions.size() >= aSizeStart) { + WitcheryExtras.log( + 1, + "Failed to remove Infusion: " + + (infusion != null + ? infusion.toString() + " | " + infusion.infusionID + " | " + : infusion.infusionID)); + } + return infusions.size() < aSizeStart; + } + + /* + * Spinning Recipes + */ + + public static synchronized boolean addSpinningWheelRecipe( + ItemStack result, ItemStack fibre, ItemStack... modifiers) { + if (result == null || fibre == null) { + return false; + } + SpinningRecipes.instance().addRecipe(result, fibre, modifiers); + return true; + } + + public static boolean removeSpinningWheelRecipe(ItemStack result, ItemStack fibre, ItemStack... modifiers) { + SpinningRecipe aRecipeToRemove = null; + for (SpinningRecipe aRecipe : SpinningRecipes.instance().recipes) { + if (Utils.areStacksEqual(fibre, aRecipe.fibre)) { + if (Utils.areStacksEqual(result, aRecipe.result)) { + if (modifiers.length > 0 + && aRecipe.modifiers.length > 0 + && modifiers.length == aRecipe.modifiers.length) { + aRecipeToRemove = aRecipe; + break; + } + } + } + } + if (aRecipeToRemove != null) { + return SpinningRecipes.instance().recipes.remove(aRecipeToRemove); + } + return false; + } + + public static boolean removeSpinningRecipe(SpinningRecipe mRecipe) { + return removeSpinningWheelRecipe(mRecipe.result, mRecipe.fibre, mRecipe.modifiers); + } } diff --git a/src/main/java/alkalus/main/core/util/WitchesOvenUtils.java b/src/main/java/alkalus/main/core/util/WitchesOvenUtils.java index ca8c3d8..d11b206 100644 --- a/src/main/java/alkalus/main/core/util/WitchesOvenUtils.java +++ b/src/main/java/alkalus/main/core/util/WitchesOvenUtils.java @@ -1,20 +1,15 @@ package alkalus.main.core.util; -import java.util.ArrayList; - +import alkalus.main.core.crafting.OvenRecipes; +import alkalus.main.core.crafting.OvenRecipes.OvenRecipe; import com.emoniph.witchery.Witchery; import com.emoniph.witchery.blocks.BlockWitchesOven; import com.emoniph.witchery.blocks.BlockWitchesOven.TileEntityWitchesOven; import com.emoniph.witchery.util.Config; import com.emoniph.witchery.util.Log; - -import alkalus.main.core.crafting.OvenRecipes; -import alkalus.main.core.crafting.OvenRecipes.OvenRecipe; import net.minecraft.block.Block; import net.minecraft.init.Blocks; -import net.minecraft.init.Items; import net.minecraft.item.Item; -import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.nbt.NBTBase; @@ -25,32 +20,38 @@ @SuppressWarnings("unused") public class WitchesOvenUtils { - private static final int COOK_TIME = 180; - private static final double FUNNEL_CHANCE = 0.25; - private static final double FILTERED_FUNNEL_CHANCE = 0.3; - private static final double DOUBLED_FILTERED_FUNNEL_CHANCE = 0.8; - private static final int SLOT_TO_COOK = 0; - private static final int SLOT_FUEL = 1; - private static final int SLOT_COOKED = 2; - private static final int SLOT_BY_PRODUCT = 3; - private static final int SLOT_JARS = 4; - private static final int[] slots_top = new int[] { 0, 4 }; - private static final int[] slots_bottom = new int[] { 4, 1 }; - private static final int[] slots_sides = new int[] { 3, 2, 4, 1 }; - - public static ItemStack[] getFurnaceItemStacks(TileEntityWitchesOven aTile) { - return (ItemStack[]) ReflectionUtils.getFieldValue(ReflectionUtils.getField(TileEntityWitchesOven.class, "furnaceItemStacks"), aTile); - } - - public static int[] getSlotsTop(TileEntityWitchesOven aTile) { - return (int[]) ReflectionUtils.getFieldValue(ReflectionUtils.getField(TileEntityWitchesOven.class, "slots_top"), aTile); - } - public static int[] getSlotsBottom(TileEntityWitchesOven aTile) { - return (int[]) ReflectionUtils.getFieldValue(ReflectionUtils.getField(TileEntityWitchesOven.class, "slots_bottom"), aTile); - } - public static int[] getSlotsSides(TileEntityWitchesOven aTile) { - return (int[]) ReflectionUtils.getFieldValue(ReflectionUtils.getField(TileEntityWitchesOven.class, "slots_sides"), aTile); - } + private static final int COOK_TIME = 180; + private static final double FUNNEL_CHANCE = 0.25; + private static final double FILTERED_FUNNEL_CHANCE = 0.3; + private static final double DOUBLED_FILTERED_FUNNEL_CHANCE = 0.8; + private static final int SLOT_TO_COOK = 0; + private static final int SLOT_FUEL = 1; + private static final int SLOT_COOKED = 2; + private static final int SLOT_BY_PRODUCT = 3; + private static final int SLOT_JARS = 4; + private static final int[] slots_top = new int[] {0, 4}; + private static final int[] slots_bottom = new int[] {4, 1}; + private static final int[] slots_sides = new int[] {3, 2, 4, 1}; + + public static ItemStack[] getFurnaceItemStacks(TileEntityWitchesOven aTile) { + return (ItemStack[]) ReflectionUtils.getFieldValue( + ReflectionUtils.getField(TileEntityWitchesOven.class, "furnaceItemStacks"), aTile); + } + + public static int[] getSlotsTop(TileEntityWitchesOven aTile) { + return (int[]) ReflectionUtils.getFieldValue( + ReflectionUtils.getField(TileEntityWitchesOven.class, "slots_top"), aTile); + } + + public static int[] getSlotsBottom(TileEntityWitchesOven aTile) { + return (int[]) ReflectionUtils.getFieldValue( + ReflectionUtils.getField(TileEntityWitchesOven.class, "slots_bottom"), aTile); + } + + public static int[] getSlotsSides(TileEntityWitchesOven aTile) { + return (int[]) ReflectionUtils.getFieldValue( + ReflectionUtils.getField(TileEntityWitchesOven.class, "slots_sides"), aTile); + } public static void updateEntity(TileEntityWitchesOven aTile) { final boolean flag = aTile.furnaceBurnTime > 0; @@ -59,10 +60,10 @@ public static void updateEntity(TileEntityWitchesOven aTile) { --aTile.furnaceBurnTime; } if (!aTile.getWorldObj().isRemote) { - - if (canSmelt(aTile)) { - - // Add Fuel + + if (canSmelt(aTile)) { + + // Add Fuel if (aTile.furnaceBurnTime == 0) { final int itemBurnTime = TileEntityFurnace.getItemBurnTime(getFuelSlot(aTile)); aTile.furnaceBurnTime = itemBurnTime; @@ -73,12 +74,12 @@ public static void updateEntity(TileEntityWitchesOven aTile) { final ItemStack itemStack = getFuelSlot(aTile); --itemStack.stackSize; if (getFuelSlot(aTile).stackSize == 0) { - setFuelSlot(aTile, getFuelSlot(aTile).getItem().getContainerItem(getFuelSlot(aTile))); + setFuelSlot(aTile, getFuelSlot(aTile).getItem().getContainerItem(getFuelSlot(aTile))); } } } } - + // Try do recipe if (aTile.isBurning()) { ++aTile.furnaceCookTime; @@ -87,22 +88,15 @@ public static void updateEntity(TileEntityWitchesOven aTile) { smeltItem(aTile); aDoBlockUpdate = true; } - } - else { + } else { aTile.furnaceCookTime = 0; } - - - - } - - - - + } if (flag != aTile.furnaceBurnTime > 0) { aDoBlockUpdate = true; - BlockWitchesOven.updateWitchesOvenBlockState(aTile.furnaceBurnTime > 0, aTile.getWorldObj(), aTile.xCoord, aTile.yCoord, aTile.zCoord); + BlockWitchesOven.updateWitchesOvenBlockState( + aTile.furnaceBurnTime > 0, aTile.getWorldObj(), aTile.xCoord, aTile.yCoord, aTile.zCoord); } } if (aDoBlockUpdate) { @@ -111,368 +105,369 @@ public static void updateEntity(TileEntityWitchesOven aTile) { } } - public static int getEmptyJarCount(TileEntityWitchesOven aTile) { - ItemStack aJarStack = getEmptyJarSlot(aTile); - return aJarStack != null ? aJarStack.stackSize : 0; - } - + ItemStack aJarStack = getEmptyJarSlot(aTile); + return aJarStack != null ? aJarStack.stackSize : 0; + } + public static ItemStack getInputSlot(TileEntityWitchesOven aTile) { - ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_TO_COOK]; - return aJarStack != null ? aJarStack : null; + ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_TO_COOK]; + return aJarStack != null ? aJarStack : null; } + public static ItemStack getFuelSlot(TileEntityWitchesOven aTile) { - ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_FUEL]; - return aJarStack != null ? aJarStack : null; + ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_FUEL]; + return aJarStack != null ? aJarStack : null; } + public static ItemStack getOutputSlot(TileEntityWitchesOven aTile) { - ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_COOKED]; - return aJarStack != null ? aJarStack : null; + ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_COOKED]; + return aJarStack != null ? aJarStack : null; } + public static ItemStack getFumeOutputSlot(TileEntityWitchesOven aTile) { - ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_BY_PRODUCT]; - return aJarStack != null ? aJarStack : null; + ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_BY_PRODUCT]; + return aJarStack != null ? aJarStack : null; } + public static ItemStack getEmptyJarSlot(TileEntityWitchesOven aTile) { - ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_JARS]; - return aJarStack != null ? aJarStack : null; + ItemStack aJarStack = getFurnaceItemStacks(aTile)[SLOT_JARS]; + return aJarStack != null ? aJarStack : null; } - + public static void setInputSlot(TileEntityWitchesOven aTile, ItemStack aNewVal) { - getFurnaceItemStacks(aTile)[SLOT_TO_COOK] = aNewVal; + getFurnaceItemStacks(aTile)[SLOT_TO_COOK] = aNewVal; } + public static void setFuelSlot(TileEntityWitchesOven aTile, ItemStack aNewVal) { - getFurnaceItemStacks(aTile)[SLOT_FUEL] = aNewVal; + getFurnaceItemStacks(aTile)[SLOT_FUEL] = aNewVal; } + public static void setOutputSlot(TileEntityWitchesOven aTile, ItemStack aNewVal) { - getFurnaceItemStacks(aTile)[SLOT_COOKED] = aNewVal; + getFurnaceItemStacks(aTile)[SLOT_COOKED] = aNewVal; } + public static void setFumeOutputSlot(TileEntityWitchesOven aTile, ItemStack aNewVal) { - getFurnaceItemStacks(aTile)[SLOT_BY_PRODUCT] = aNewVal; + getFurnaceItemStacks(aTile)[SLOT_BY_PRODUCT] = aNewVal; } + public static void setEmptyJarSlot(TileEntityWitchesOven aTile, ItemStack aNewVal) { - getFurnaceItemStacks(aTile)[SLOT_JARS] = aNewVal; + getFurnaceItemStacks(aTile)[SLOT_JARS] = aNewVal; } + public static boolean canSmelt(TileEntityWitchesOven aTile) { + if (getInputSlot(aTile) == null) { + return false; + } + OvenRecipe aValidRecipe = null; + int aJarCount = getEmptyJarCount(aTile); + // Do we have any recipes without jar usage? + if (aJarCount == 0) { + for (OvenRecipe r : OvenRecipes.getRecipeMap()) { + if (r.jars > 0) { + continue; + } else { + if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { + aValidRecipe = r; + break; + } + } + } + } else { + for (OvenRecipe r : OvenRecipes.getRecipeMap()) { + if (r.jars > aJarCount) { + continue; + } else { + if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { + aValidRecipe = r; + break; + } + } + } + } + + if (aValidRecipe == null) { + return false; + } else { + final ItemStack itemstack = aValidRecipe.output; + final ItemStack outputSlot = getOutputSlot(aTile); + if (outputSlot == null) { + return true; + } + if (!outputSlot.isItemEqual(itemstack)) { + return false; + } + final int result = getOutputSlot(aTile).stackSize + itemstack.stackSize; + + // return result <= aTile.getInventoryStackLimit() && result <= itemstack.getMaxStackSize(); + return result <= aTile.func_70297_j_() && result <= itemstack.getMaxStackSize(); + } + } - public static boolean canSmelt(TileEntityWitchesOven aTile) { - if (getInputSlot(aTile) == null) { - return false; - } - OvenRecipe aValidRecipe = null; - int aJarCount = getEmptyJarCount(aTile); - // Do we have any recipes without jar usage? - if (aJarCount == 0) { - for (OvenRecipe r : OvenRecipes.getRecipeMap()){ - if (r.jars > 0) { - continue; - } - else { - if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { - aValidRecipe = r; - break; - } - } - } - } - else { - for (OvenRecipe r : OvenRecipes.getRecipeMap()){ - if (r.jars > aJarCount) { - continue; - } - else { - if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { - aValidRecipe = r; - break; - } - } - } - } - - if (aValidRecipe == null) { - return false; - } - else { - final ItemStack itemstack = aValidRecipe.output; - final ItemStack outputSlot = getOutputSlot(aTile); - if (outputSlot == null) { - return true; - } - if (!outputSlot.isItemEqual(itemstack)) { - return false; - } - final int result = getOutputSlot(aTile).stackSize + itemstack.stackSize; - - // return result <= aTile.getInventoryStackLimit() && result <= itemstack.getMaxStackSize(); - return result <= aTile.func_70297_j_() && result <= itemstack.getMaxStackSize(); - } - } - public static void smeltItem(TileEntityWitchesOven aTile) { - - OvenRecipe aValidRecipe = null; - int aJarCount = getEmptyJarCount(aTile); - // Do we have any recipes without jar usage? - if (aJarCount == 0) { - for (OvenRecipe r : OvenRecipes.getRecipeMap()){ - if (r.jars > 0) { - continue; - } - else { - if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { - aValidRecipe = r; - break; - } - } - } - } - else { - for (OvenRecipe r : OvenRecipes.getRecipeMap()){ - if (r.jars > aJarCount) { - continue; - } - else { - if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { - aValidRecipe = r; - break; - } - } - } - } - - if (aValidRecipe == null) { - return; - } - else { - if (canSmelt(aTile)) { - final ItemStack itemstack = FurnaceRecipes.smelting().getSmeltingResult(getInputSlot(aTile)); - if (getOutputSlot(aTile) == null) { - setOutputSlot(aTile, itemstack.copy()); - } - else if (getOutputSlot(aTile).isItemEqual(itemstack)) { - final ItemStack itemStack = getOutputSlot(aTile); - itemStack.stackSize += itemstack.stackSize; - } - generateByProduct(aTile, itemstack); - final ItemStack itemStack2 = getInputSlot(aTile); - --itemStack2.stackSize; - if (getInputSlot(aTile).stackSize <= 0) { - setInputSlot(aTile, null); - } - } - } + + OvenRecipe aValidRecipe = null; + int aJarCount = getEmptyJarCount(aTile); + // Do we have any recipes without jar usage? + if (aJarCount == 0) { + for (OvenRecipe r : OvenRecipes.getRecipeMap()) { + if (r.jars > 0) { + continue; + } else { + if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { + aValidRecipe = r; + break; + } + } + } + } else { + for (OvenRecipe r : OvenRecipes.getRecipeMap()) { + if (r.jars > aJarCount) { + continue; + } else { + if (Utils.areStacksEqual(r.inputs, getInputSlot(aTile))) { + aValidRecipe = r; + break; + } + } + } + } + + if (aValidRecipe == null) { + return; + } else { + if (canSmelt(aTile)) { + final ItemStack itemstack = FurnaceRecipes.smelting().getSmeltingResult(getInputSlot(aTile)); + if (getOutputSlot(aTile) == null) { + setOutputSlot(aTile, itemstack.copy()); + } else if (getOutputSlot(aTile).isItemEqual(itemstack)) { + final ItemStack itemStack = getOutputSlot(aTile); + itemStack.stackSize += itemstack.stackSize; + } + generateByProduct(aTile, itemstack); + final ItemStack itemStack2 = getInputSlot(aTile); + --itemStack2.stackSize; + if (getInputSlot(aTile).stackSize <= 0) { + setInputSlot(aTile, null); + } + } + } + } + + public static int getFumeFunnels(TileEntityWitchesOven aTile) { + int funnels = 0; + final int meta = aTile.getWorldObj().getBlockMetadata(aTile.xCoord, aTile.yCoord, aTile.zCoord); + switch (meta) { + case 2: + case 3: { + funnels += (isFumeFunnel(aTile, aTile.xCoord - 1, aTile.yCoord, aTile.zCoord, meta) ? 1 : 0); + funnels += (isFumeFunnel(aTile, aTile.xCoord + 1, aTile.yCoord, aTile.zCoord, meta) ? 1 : 0); + break; + } + case 4: + case 5: { + funnels += (isFumeFunnel(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord - 1, meta) ? 1 : 0); + funnels += (isFumeFunnel(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord + 1, meta) ? 1 : 0); + break; + } + } + funnels += (isFumeFunnel(aTile, aTile.xCoord, aTile.yCoord + 1, aTile.zCoord, meta) ? 1 : 0); + return funnels; + } + + public static boolean isFumeFunnel( + TileEntityWitchesOven aTile, final int xCoord, final int yCoord, final int zCoord, final int meta) { + final Block block = aTile.getWorldObj().getBlock(xCoord, yCoord, zCoord); + return (block == Witchery.Blocks.OVEN_FUMEFUNNEL || block == Witchery.Blocks.OVEN_FUMEFUNNEL_FILTERED) + && aTile.getWorldObj().getBlockMetadata(xCoord, yCoord, zCoord) == meta; + } + + public static double getFumeFunnelsChance(TileEntityWitchesOven aTile) { + double funnels = 0.0; + switch (aTile.getWorldObj().getBlockMetadata(aTile.xCoord, aTile.yCoord, aTile.zCoord)) { + case 2: { + funnels += getFumeFunnelChance(aTile, aTile.xCoord + 1, aTile.yCoord, aTile.zCoord, 2); + funnels += getFumeFunnelChance(aTile, aTile.xCoord - 1, aTile.yCoord, aTile.zCoord, 2); + break; + } + case 3: { + funnels += getFumeFunnelChance(aTile, aTile.xCoord + 1, aTile.yCoord, aTile.zCoord, 3); + funnels += getFumeFunnelChance(aTile, aTile.xCoord - 1, aTile.yCoord, aTile.zCoord, 3); + break; + } + case 4: { + funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord + 1, 4); + funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord - 1, 4); + break; + } + case 5: { + funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord + 1, 5); + funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord - 1, 5); + break; + } + } + return funnels; + } + + public static double getFumeFunnelChance( + TileEntityWitchesOven aTile, final int x, final int y, final int z, final int meta) { + final Block block = aTile.getWorldObj().getBlock(x, y, z); + if (block == Witchery.Blocks.OVEN_FUMEFUNNEL) { + if (aTile.getWorldObj().getBlockMetadata(x, y, z) == meta) { + return 0.25; + } + } else if (block == Witchery.Blocks.OVEN_FUMEFUNNEL_FILTERED + && aTile.getWorldObj().getBlockMetadata(x, y, z) == meta) { + return Config.instance().doubleFumeFilterChance ? 0.8 : 0.3; + } + return 0.0; + } + + public static int getCookTime(TileEntityWitchesOven aTile) { + final int time = 180 - 20 * getFumeFunnels(aTile); + return time; + } + + public static void generateByProduct(TileEntityWitchesOven aTile, final ItemStack itemstack) { + try { + final double BASE_CHANCE = 0.3; + final double funnels = getFumeFunnelsChance(aTile); + Log.instance() + .debug("" + getInputSlot(aTile) + ": " + + getInputSlot(aTile).getItem().getUnlocalizedName()); + if (aTile.getWorldObj().rand.nextDouble() <= Math.min(0.3 + funnels, 1.0) + && getEmptyJarSlot(aTile) != null) { + if (getInputSlot(aTile).getItem() == Item.getItemFromBlock(Blocks.sapling) + && getInputSlot(aTile).getItemDamage() != 3) { + switch (getInputSlot(aTile).getItemDamage()) { + case 0: { + createByProduct(aTile, Witchery.Items.GENERIC.itemExhaleOfTheHornedOne.createStack(1)); + break; + } + case 1: { + createByProduct(aTile, Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); + break; + } + case 2: { + createByProduct(aTile, Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); + break; + } + } + } else if (getInputSlot(aTile).getItem() == Item.getItemFromBlock(Witchery.Blocks.SAPLING)) { + switch (getInputSlot(aTile).getItemDamage()) { + case 0: { + createByProduct(aTile, Witchery.Items.GENERIC.itemWhiffOfMagic.createStack(1)); + break; + } + case 1: { + createByProduct(aTile, Witchery.Items.GENERIC.itemReekOfMisfortune.createStack(1)); + break; + } + case 2: { + createByProduct(aTile, Witchery.Items.GENERIC.itemOdourOfPurity.createStack(1)); + break; + } + } + } else if (getInputSlot(aTile).getUnlocalizedName().equals("tile.bop.saplings") + && getInputSlot(aTile).getItemDamage() == 6) { + createByProduct(aTile, Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); + } else if (isForestrySapling(getInputSlot(aTile))) { + final NBTBase tag = getInputSlot(aTile).getTagCompound().getTag("Genome"); + if (tag != null && tag instanceof NBTTagCompound) { + final NBTTagCompound compound = (NBTTagCompound) tag; + if (compound.hasKey("Chromosomes") && compound.getTag("Chromosomes") instanceof NBTTagList) { + final NBTTagList list = compound.getTagList("Chromosomes", 10); + if (list != null && list.tagCount() > 0) { + final NBTBase chromoBase = (NBTBase) list.getCompoundTagAt(0); + if (chromoBase != null && chromoBase instanceof NBTTagCompound) { + final NBTTagCompound chromosome = (NBTTagCompound) chromoBase; + if (chromosome.hasKey("UID0")) { + final String treeType = chromosome.getString("UID0"); + if (treeType != null) { + Log.instance().debug("Forestry tree: " + treeType); + if (treeType.equals("forestry.treeOak")) { + createByProduct( + aTile, + Witchery.Items.GENERIC.itemExhaleOfTheHornedOne.createStack(1)); + } else if (treeType.equals("forestry.treeSpruce")) { + createByProduct( + aTile, Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); + } else if (treeType.equals("forestry.treeBirch")) { + createByProduct( + aTile, + Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); + } + } + } + } + } + } + } + } else { + createByProduct(aTile, Witchery.Items.GENERIC.itemFoulFume.createStack(1)); + } + } + } catch (Throwable e) { + Log.instance().warning(e, "Exception occured while generating a by product from a witches oven"); + } } - public static int getFumeFunnels(TileEntityWitchesOven aTile) { - int funnels = 0; - final int meta = aTile.getWorldObj().getBlockMetadata(aTile.xCoord, aTile.yCoord, aTile.zCoord); - switch (meta) { - case 2: - case 3: { - funnels += (isFumeFunnel(aTile, aTile.xCoord - 1, aTile.yCoord, aTile.zCoord, meta) ? 1 : 0); - funnels += (isFumeFunnel(aTile, aTile.xCoord + 1, aTile.yCoord, aTile.zCoord, meta) ? 1 : 0); - break; - } - case 4: - case 5: { - funnels += (isFumeFunnel(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord - 1, meta) ? 1 : 0); - funnels += (isFumeFunnel(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord + 1, meta) ? 1 : 0); - break; - } - } - funnels += (isFumeFunnel(aTile, aTile.xCoord, aTile.yCoord + 1, aTile.zCoord, meta) ? 1 : 0); - return funnels; - } - - public static boolean isFumeFunnel(TileEntityWitchesOven aTile, final int xCoord, final int yCoord, final int zCoord, final int meta) { - final Block block = aTile.getWorldObj().getBlock(xCoord, yCoord, zCoord); - return (block == Witchery.Blocks.OVEN_FUMEFUNNEL || block == Witchery.Blocks.OVEN_FUMEFUNNEL_FILTERED) && aTile.getWorldObj().getBlockMetadata(xCoord, yCoord, zCoord) == meta; - } - - public static double getFumeFunnelsChance(TileEntityWitchesOven aTile) { - double funnels = 0.0; - switch (aTile.getWorldObj().getBlockMetadata(aTile.xCoord, aTile.yCoord, aTile.zCoord)) { - case 2: { - funnels += getFumeFunnelChance(aTile, aTile.xCoord + 1, aTile.yCoord, aTile.zCoord, 2); - funnels += getFumeFunnelChance(aTile, aTile.xCoord - 1, aTile.yCoord, aTile.zCoord, 2); - break; - } - case 3: { - funnels += getFumeFunnelChance(aTile, aTile.xCoord + 1, aTile.yCoord, aTile.zCoord, 3); - funnels += getFumeFunnelChance(aTile, aTile.xCoord - 1, aTile.yCoord, aTile.zCoord, 3); - break; - } - case 4: { - funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord + 1, 4); - funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord - 1, 4); - break; - } - case 5: { - funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord + 1, 5); - funnels += getFumeFunnelChance(aTile, aTile.xCoord, aTile.yCoord, aTile.zCoord - 1, 5); - break; - } - } - return funnels; - } - - public static double getFumeFunnelChance(TileEntityWitchesOven aTile, final int x, final int y, final int z, final int meta) { - final Block block = aTile.getWorldObj().getBlock(x, y, z); - if (block == Witchery.Blocks.OVEN_FUMEFUNNEL) { - if (aTile.getWorldObj().getBlockMetadata(x, y, z) == meta) { - return 0.25; - } - } - else if (block == Witchery.Blocks.OVEN_FUMEFUNNEL_FILTERED && aTile.getWorldObj().getBlockMetadata(x, y, z) == meta) { - return Config.instance().doubleFumeFilterChance ? 0.8 : 0.3; - } - return 0.0; - } - - public static int getCookTime(TileEntityWitchesOven aTile) { - final int time = 180 - 20 * getFumeFunnels(aTile); - return time; - } - - public static void generateByProduct(TileEntityWitchesOven aTile, final ItemStack itemstack) { - try { - final double BASE_CHANCE = 0.3; - final double funnels = getFumeFunnelsChance(aTile); - Log.instance().debug("" + getInputSlot(aTile) + ": " + getInputSlot(aTile).getItem().getUnlocalizedName()); - if (aTile.getWorldObj().rand.nextDouble() <= Math.min(0.3 + funnels, 1.0) && getEmptyJarSlot(aTile) != null) { - if (getInputSlot(aTile).getItem() == Item.getItemFromBlock(Blocks.sapling) && getInputSlot(aTile).getItemDamage() != 3) { - switch (getInputSlot(aTile).getItemDamage()) { - case 0: { - createByProduct(aTile, Witchery.Items.GENERIC.itemExhaleOfTheHornedOne.createStack(1)); - break; - } - case 1: { - createByProduct(aTile, Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); - break; - } - case 2: { - createByProduct(aTile, Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); - break; - } - } - } - else if (getInputSlot(aTile).getItem() == Item.getItemFromBlock(Witchery.Blocks.SAPLING)) { - switch (getInputSlot(aTile).getItemDamage()) { - case 0: { - createByProduct(aTile, Witchery.Items.GENERIC.itemWhiffOfMagic.createStack(1)); - break; - } - case 1: { - createByProduct(aTile, Witchery.Items.GENERIC.itemReekOfMisfortune.createStack(1)); - break; - } - case 2: { - createByProduct(aTile, Witchery.Items.GENERIC.itemOdourOfPurity.createStack(1)); - break; - } - } - } - else if (getInputSlot(aTile).getUnlocalizedName().equals("tile.bop.saplings") && getInputSlot(aTile).getItemDamage() == 6) { - createByProduct(aTile, Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); - } - else if (isForestrySapling(getInputSlot(aTile))) { - final NBTBase tag = getInputSlot(aTile).getTagCompound().getTag("Genome"); - if (tag != null && tag instanceof NBTTagCompound) { - final NBTTagCompound compound = (NBTTagCompound)tag; - if (compound.hasKey("Chromosomes") && compound.getTag("Chromosomes") instanceof NBTTagList) { - final NBTTagList list = compound.getTagList("Chromosomes", 10); - if (list != null && list.tagCount() > 0) { - final NBTBase chromoBase = (NBTBase)list.getCompoundTagAt(0); - if (chromoBase != null && chromoBase instanceof NBTTagCompound) { - final NBTTagCompound chromosome = (NBTTagCompound)chromoBase; - if (chromosome.hasKey("UID0")) { - final String treeType = chromosome.getString("UID0"); - if (treeType != null) { - Log.instance().debug("Forestry tree: " + treeType); - if (treeType.equals("forestry.treeOak")) { - createByProduct(aTile, Witchery.Items.GENERIC.itemExhaleOfTheHornedOne.createStack(1)); - } - else if (treeType.equals("forestry.treeSpruce")) { - createByProduct(aTile, Witchery.Items.GENERIC.itemHintOfRebirth.createStack(1)); - } - else if (treeType.equals("forestry.treeBirch")) { - createByProduct(aTile, Witchery.Items.GENERIC.itemBreathOfTheGoddess.createStack(1)); - } - } - } - } - } - } - } - } - else { - createByProduct(aTile, Witchery.Items.GENERIC.itemFoulFume.createStack(1)); - } - } - } - catch (Throwable e) { - Log.instance().warning(e, "Exception occured while generating a by product from a witches oven"); - } - } - - public static void createByProduct(TileEntityWitchesOven aTile, final ItemStack byProduct) { - final int BY_PRODUCT_INDEX = 3; - if (getFumeOutputSlot(aTile) == null) { - setFumeOutputSlot(aTile, byProduct); - final ItemStack itemStack = getEmptyJarSlot(aTile); - if (--itemStack.stackSize <= 0) { - setEmptyJarSlot(aTile, null); - } - } - else if (getFumeOutputSlot(aTile).isItemEqual(byProduct) && getFumeOutputSlot(aTile).stackSize + byProduct.stackSize < getFumeOutputSlot(aTile).getMaxStackSize()) { - final ItemStack itemStack2 = getFumeOutputSlot(aTile); - itemStack2.stackSize += byProduct.stackSize; - final ItemStack itemStack3 = getEmptyJarSlot(aTile); - if (--itemStack3.stackSize <= 0) { - setEmptyJarSlot(aTile, null); - } - } - } - - private static boolean isForestrySapling(ItemStack aSap) { - if (aSap != null && aSap.hasTagCompound() && aSap.getTagCompound().hasKey("Genome")) { - return true; - } - return false; - } - - public static ItemStack getVanillaEquivForForestrySapling(ItemStack aSap) { - if (isForestrySapling(aSap)) { - final NBTBase tag = aSap.getTagCompound().getTag("Genome"); - if (tag != null && tag instanceof NBTTagCompound) { - final NBTTagCompound compound = (NBTTagCompound)tag; - if (compound.hasKey("Chromosomes") && compound.getTag("Chromosomes") instanceof NBTTagList) { - final NBTTagList list = compound.getTagList("Chromosomes", 10); - if (list != null && list.tagCount() > 0) { - final NBTBase chromoBase = (NBTBase)list.getCompoundTagAt(0); - if (chromoBase != null && chromoBase instanceof NBTTagCompound) { - final NBTTagCompound chromosome = (NBTTagCompound)chromoBase; - if (chromosome.hasKey("UID0")) { - final String treeType = chromosome.getString("UID0"); - if (treeType != null) { - Log.instance().debug("Forestry tree: " + treeType); - if (treeType.equals("forestry.treeOak")) { - return new ItemStack(Blocks.sapling, 1, 0); - } - else if (treeType.equals("forestry.treeSpruce")) { - return new ItemStack(Blocks.sapling, 1, 1); - } - else if (treeType.equals("forestry.treeBirch")) { - return new ItemStack(Blocks.sapling, 1, 2); - } - } - } - } - } - } - } - } - return null; - } + public static void createByProduct(TileEntityWitchesOven aTile, final ItemStack byProduct) { + final int BY_PRODUCT_INDEX = 3; + if (getFumeOutputSlot(aTile) == null) { + setFumeOutputSlot(aTile, byProduct); + final ItemStack itemStack = getEmptyJarSlot(aTile); + if (--itemStack.stackSize <= 0) { + setEmptyJarSlot(aTile, null); + } + } else if (getFumeOutputSlot(aTile).isItemEqual(byProduct) + && getFumeOutputSlot(aTile).stackSize + byProduct.stackSize + < getFumeOutputSlot(aTile).getMaxStackSize()) { + final ItemStack itemStack2 = getFumeOutputSlot(aTile); + itemStack2.stackSize += byProduct.stackSize; + final ItemStack itemStack3 = getEmptyJarSlot(aTile); + if (--itemStack3.stackSize <= 0) { + setEmptyJarSlot(aTile, null); + } + } + } + private static boolean isForestrySapling(ItemStack aSap) { + if (aSap != null && aSap.hasTagCompound() && aSap.getTagCompound().hasKey("Genome")) { + return true; + } + return false; + } + + public static ItemStack getVanillaEquivForForestrySapling(ItemStack aSap) { + if (isForestrySapling(aSap)) { + final NBTBase tag = aSap.getTagCompound().getTag("Genome"); + if (tag != null && tag instanceof NBTTagCompound) { + final NBTTagCompound compound = (NBTTagCompound) tag; + if (compound.hasKey("Chromosomes") && compound.getTag("Chromosomes") instanceof NBTTagList) { + final NBTTagList list = compound.getTagList("Chromosomes", 10); + if (list != null && list.tagCount() > 0) { + final NBTBase chromoBase = (NBTBase) list.getCompoundTagAt(0); + if (chromoBase != null && chromoBase instanceof NBTTagCompound) { + final NBTTagCompound chromosome = (NBTTagCompound) chromoBase; + if (chromosome.hasKey("UID0")) { + final String treeType = chromosome.getString("UID0"); + if (treeType != null) { + Log.instance().debug("Forestry tree: " + treeType); + if (treeType.equals("forestry.treeOak")) { + return new ItemStack(Blocks.sapling, 1, 0); + } else if (treeType.equals("forestry.treeSpruce")) { + return new ItemStack(Blocks.sapling, 1, 1); + } else if (treeType.equals("forestry.treeBirch")) { + return new ItemStack(Blocks.sapling, 1, 2); + } + } + } + } + } + } + } + } + return null; + } } diff --git a/src/main/java/alkalus/main/core/util/threadly/RunnableChain.java b/src/main/java/alkalus/main/core/util/threadly/RunnableChain.java index d5258af..4796f83 100644 --- a/src/main/java/alkalus/main/core/util/threadly/RunnableChain.java +++ b/src/main/java/alkalus/main/core/util/threadly/RunnableChain.java @@ -1,109 +1,106 @@ package alkalus.main.core.util.threadly; +import alkalus.main.core.WitcheryExtras; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Collections; import java.util.Iterator; -import alkalus.main.core.WitcheryExtras; - /** * A class to chain multiple runnables to later be run together, within the same thread. - * + * * @since 1.0.0 */ public class RunnableChain implements Runnable { - protected final boolean exceptionStopsChain; - private final Iterable toRun; - - /** - * Constructs a runnable chain with a provided list of runnables to iterate over. - * - * @param exceptionStopsChain {@code true} for uncaught exception stops the execution of the chain - * @param toRun Iterable collection of runnables to run - */ - public RunnableChain(boolean exceptionStopsChain, - Iterable toRun) { - if (toRun == null) { - toRun = Collections.emptyList(); - } + protected final boolean exceptionStopsChain; + private final Iterable toRun; - this.exceptionStopsChain = exceptionStopsChain; - this.toRun = toRun; - WitcheryExtras.log(0, "[Module Loader] Loading Module with "+toRun.spliterator().getExactSizeIfKnown()+" objects."); - - } + /** + * Constructs a runnable chain with a provided list of runnables to iterate over. + * + * @param exceptionStopsChain {@code true} for uncaught exception stops the execution of the chain + * @param toRun Iterable collection of runnables to run + */ + public RunnableChain(boolean exceptionStopsChain, Iterable toRun) { + if (toRun == null) { + toRun = Collections.emptyList(); + } - @Override - public void run() { - if (exceptionStopsChain) { - runExceptionsCascade(); - } else { - runIsolated(); - } - } + this.exceptionStopsChain = exceptionStopsChain; + this.toRun = toRun; + WitcheryExtras.log( + 0, "[Module Loader] Loading Module with " + toRun.spliterator().getExactSizeIfKnown() + " objects."); + } - /** - * Iterates through the toRun list, executing along the way. If any exceptions are thrown, they - * will be propagated out of this call. - */ - protected void runExceptionsCascade() { - Iterator it = toRun.iterator(); - while (it.hasNext()) { - it.next().run(); - } - } + @Override + public void run() { + if (exceptionStopsChain) { + runExceptionsCascade(); + } else { + runIsolated(); + } + } - /** - * Iterates through the toRun list, executing along the way. If any exceptions are thrown, they - * will be handled to {@link ExceptionUtils} and will not stop future executions. - */ - protected void runIsolated() { - Iterator it = toRun.iterator(); - while (it.hasNext()) { - runRunnable(it.next()); - } - } + /** + * Iterates through the toRun list, executing along the way. If any exceptions are thrown, they + * will be propagated out of this call. + */ + protected void runExceptionsCascade() { + Iterator it = toRun.iterator(); + while (it.hasNext()) { + it.next().run(); + } + } - /** - * Invokes {@link Runnable#run()} on the provided runnable on this thread, ensuring that no - * throwables are thrown out of this invocation. If any throwable's are thrown, they will be - * provided to {@link #handleException(Throwable)}. - * - * @param r Runnable to invoke, can not be null - */ - public static void runRunnable(Runnable r) { - try { - r.run(); - } catch (Throwable t) { - handleException(t); - } - } + /** + * Iterates through the toRun list, executing along the way. If any exceptions are thrown, they + * will be handled to {@link ExceptionUtils} and will not stop future executions. + */ + protected void runIsolated() { + Iterator it = toRun.iterator(); + while (it.hasNext()) { + runRunnable(it.next()); + } + } - /** - * This call handles an uncaught throwable. If a default uncaught exception handler is set, - * then that will be called to handle the uncaught exception. If none is set, then the - * exception will be printed out to standard error. - * - * @param t throwable to handle - */ - public static void handleException(Throwable t) { - if (t == null) { - return; - } - try { - Thread currentThread = Thread.currentThread(); - UncaughtExceptionHandler ueHandler = currentThread.getUncaughtExceptionHandler(); - ueHandler.uncaughtException(currentThread, t); - } catch (Throwable handlerThrown) { - try { - System.err.println("Error handling exception: "); - t.printStackTrace(); - System.err.println("Error thrown when handling exception: "); - handlerThrown.printStackTrace(); - } catch (Throwable ignored) { - // sigh...I give up - } - } - } + /** + * Invokes {@link Runnable#run()} on the provided runnable on this thread, ensuring that no + * throwables are thrown out of this invocation. If any throwable's are thrown, they will be + * provided to {@link #handleException(Throwable)}. + * + * @param r Runnable to invoke, can not be null + */ + public static void runRunnable(Runnable r) { + try { + r.run(); + } catch (Throwable t) { + handleException(t); + } + } + /** + * This call handles an uncaught throwable. If a default uncaught exception handler is set, + * then that will be called to handle the uncaught exception. If none is set, then the + * exception will be printed out to standard error. + * + * @param t throwable to handle + */ + public static void handleException(Throwable t) { + if (t == null) { + return; + } + try { + Thread currentThread = Thread.currentThread(); + UncaughtExceptionHandler ueHandler = currentThread.getUncaughtExceptionHandler(); + ueHandler.uncaughtException(currentThread, t); + } catch (Throwable handlerThrown) { + try { + System.err.println("Error handling exception: "); + t.printStackTrace(); + System.err.println("Error thrown when handling exception: "); + handlerThrown.printStackTrace(); + } catch (Throwable ignored) { + // sigh...I give up + } + } + } } diff --git a/src/main/java/alkalus/main/nei/NEI_Config.java b/src/main/java/alkalus/main/nei/NEI_Config.java index a3a23bc..07b9765 100644 --- a/src/main/java/alkalus/main/nei/NEI_Config.java +++ b/src/main/java/alkalus/main/nei/NEI_Config.java @@ -1,13 +1,12 @@ package alkalus.main.nei; -import com.emoniph.witchery.Witchery; -import com.emoniph.witchery.integration.NEIHighlightHandler; -import com.emoniph.witchery.util.Config; - import alkalus.main.core.WitcheryExtras; import codechicken.nei.api.API; import codechicken.nei.api.IConfigureNEI; import codechicken.nei.api.IHighlightHandler; +import com.emoniph.witchery.Witchery; +import com.emoniph.witchery.integration.NEIHighlightHandler; +import com.emoniph.witchery.util.Config; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import net.minecraft.block.Block; @@ -15,86 +14,92 @@ public class NEI_Config implements IConfigureNEI { - public void loadConfig() { - if (Loader.isModLoaded("NotEnoughItems") && Config.instance().allowModIntegration && Config.instance().allowNotEnoughItems) { - WitcheryExtras.log(0, "Detected NEI, registering our own custom recipe handlers."); - API.registerRecipeHandler(new NEI_Handler_Oven()); - API.registerUsageHandler(new NEI_Handler_Oven()); - API.registerRecipeHandler(new NEI_Handler_Distillery()); - API.registerUsageHandler(new NEI_Handler_Distillery()); - API.registerRecipeHandler(new NEI_Handler_Kettle()); - API.registerUsageHandler(new NEI_Handler_Kettle()); - API.registerRecipeHandler(new NEI_Handler_Cauldron()); - API.registerUsageHandler(new NEI_Handler_Cauldron()); - API.registerRecipeHandler(new NEI_Handler_SpinningWheel()); - API.registerUsageHandler(new NEI_Handler_SpinningWheel()); - WitcheryExtras.log(0, "Handling Witchery items and registering highlight handlers."); - fixWitcheryBrokenNEI(); - } - } + public void loadConfig() { + if (Loader.isModLoaded("NotEnoughItems") + && Config.instance().allowModIntegration + && Config.instance().allowNotEnoughItems) { + WitcheryExtras.log(0, "Detected NEI, registering our own custom recipe handlers."); + API.registerRecipeHandler(new NEI_Handler_Oven()); + API.registerUsageHandler(new NEI_Handler_Oven()); + API.registerRecipeHandler(new NEI_Handler_Distillery()); + API.registerUsageHandler(new NEI_Handler_Distillery()); + API.registerRecipeHandler(new NEI_Handler_Kettle()); + API.registerUsageHandler(new NEI_Handler_Kettle()); + API.registerRecipeHandler(new NEI_Handler_Cauldron()); + API.registerUsageHandler(new NEI_Handler_Cauldron()); + API.registerRecipeHandler(new NEI_Handler_SpinningWheel()); + API.registerUsageHandler(new NEI_Handler_SpinningWheel()); + WitcheryExtras.log(0, "Handling Witchery items and registering highlight handlers."); + fixWitcheryBrokenNEI(); + } + } - private final void fixWitcheryBrokenNEI() { - API.hideItem(new ItemStack(Witchery.Blocks.OVEN_BURNING)); - API.hideItem(new ItemStack(Witchery.Blocks.DISTILLERY_BURNING)); - API.hideItem(new ItemStack(Witchery.Blocks.BARRIER)); - API.hideItem(new ItemStack(Witchery.Blocks.FORCE)); - API.hideItem(new ItemStack(Witchery.Blocks.CIRCLE)); - API.hideItem(new ItemStack(Witchery.Blocks.GLYPH_RITUAL)); - API.hideItem(new ItemStack(Witchery.Blocks.GLYPH_INFERNAL)); - API.hideItem(new ItemStack(Witchery.Blocks.GLYPH_OTHERWHERE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_BELLADONNA)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_MANDRAKE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_ARTICHOKE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_SNOWBELL)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_WORMWOOD)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_MINDRAKE)); - API.hideItem(new ItemStack(Witchery.Blocks.CHALICE)); - API.hideItem(new ItemStack(Witchery.Blocks.CANDELABRA)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.DREAM_CATCHER)); - API.hideItem(new ItemStack(Witchery.Blocks.DOOR_ALDER)); - API.hideItem(new ItemStack(Witchery.Blocks.DOOR_ROWAN)); - API.hideItem(new ItemStack(Witchery.Blocks.PERPETUAL_ICE_DOOR)); - API.hideItem(new ItemStack(Witchery.Blocks.GLOW_GLOBE)); - API.hideItem(new ItemStack(Witchery.Blocks.PLACED_ITEMSTACK)); - API.hideItem(new ItemStack(Witchery.Blocks.DEMON_HEART)); - API.hideItem(new ItemStack(Witchery.Blocks.FORCE)); - API.hideItem(new ItemStack(Witchery.Blocks.WEB)); - API.hideItem(new ItemStack(Witchery.Blocks.VINE)); - API.hideItem(new ItemStack(Witchery.Blocks.CACTUS)); - API.hideItem(new ItemStack(Witchery.Blocks.LILY)); - API.hideItem(new ItemStack(Witchery.Blocks.BREW_GAS)); - API.hideItem(new ItemStack(Witchery.Blocks.BREW_LIQUID)); - API.hideItem(new ItemStack(Witchery.Blocks.BREW)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.SLURP)); - API.hideItem(new ItemStack(Witchery.Items.BREW)); - API.hideItem(new ItemStack(Witchery.Items.BUCKET_BREW)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CURSED_BUTTON_STONE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CURSED_BUTTON_WOOD)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CURSED_LEVER)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CURSED_SNOW_PRESSURE_PLATE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CURSED_STONE_PRESSURE_PLATE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CURSED_WOODEN_DOOR)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CURSED_WOODEN_PRESSURE_PLATE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_WOLFSBANE)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.CROP_GARLIC)); - API.hideItem(new ItemStack(Witchery.Blocks.WALLGEN)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.LIGHT)); - API.hideItem(new ItemStack(Witchery.Blocks.SHADED_GLASS_ON)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.MIRROR)); - API.hideItem(new ItemStack((Block)Witchery.Blocks.MIRROR_UNBREAKABLE)); + private final void fixWitcheryBrokenNEI() { + API.hideItem(new ItemStack(Witchery.Blocks.OVEN_BURNING)); + API.hideItem(new ItemStack(Witchery.Blocks.DISTILLERY_BURNING)); + API.hideItem(new ItemStack(Witchery.Blocks.BARRIER)); + API.hideItem(new ItemStack(Witchery.Blocks.FORCE)); + API.hideItem(new ItemStack(Witchery.Blocks.CIRCLE)); + API.hideItem(new ItemStack(Witchery.Blocks.GLYPH_RITUAL)); + API.hideItem(new ItemStack(Witchery.Blocks.GLYPH_INFERNAL)); + API.hideItem(new ItemStack(Witchery.Blocks.GLYPH_OTHERWHERE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_BELLADONNA)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_MANDRAKE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_ARTICHOKE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_SNOWBELL)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_WORMWOOD)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_MINDRAKE)); + API.hideItem(new ItemStack(Witchery.Blocks.CHALICE)); + API.hideItem(new ItemStack(Witchery.Blocks.CANDELABRA)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.DREAM_CATCHER)); + API.hideItem(new ItemStack(Witchery.Blocks.DOOR_ALDER)); + API.hideItem(new ItemStack(Witchery.Blocks.DOOR_ROWAN)); + API.hideItem(new ItemStack(Witchery.Blocks.PERPETUAL_ICE_DOOR)); + API.hideItem(new ItemStack(Witchery.Blocks.GLOW_GLOBE)); + API.hideItem(new ItemStack(Witchery.Blocks.PLACED_ITEMSTACK)); + API.hideItem(new ItemStack(Witchery.Blocks.DEMON_HEART)); + API.hideItem(new ItemStack(Witchery.Blocks.FORCE)); + API.hideItem(new ItemStack(Witchery.Blocks.WEB)); + API.hideItem(new ItemStack(Witchery.Blocks.VINE)); + API.hideItem(new ItemStack(Witchery.Blocks.CACTUS)); + API.hideItem(new ItemStack(Witchery.Blocks.LILY)); + API.hideItem(new ItemStack(Witchery.Blocks.BREW_GAS)); + API.hideItem(new ItemStack(Witchery.Blocks.BREW_LIQUID)); + API.hideItem(new ItemStack(Witchery.Blocks.BREW)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.SLURP)); + API.hideItem(new ItemStack(Witchery.Items.BREW)); + API.hideItem(new ItemStack(Witchery.Items.BUCKET_BREW)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CURSED_BUTTON_STONE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CURSED_BUTTON_WOOD)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CURSED_LEVER)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CURSED_SNOW_PRESSURE_PLATE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CURSED_STONE_PRESSURE_PLATE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CURSED_WOODEN_DOOR)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CURSED_WOODEN_PRESSURE_PLATE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_WOLFSBANE)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.CROP_GARLIC)); + API.hideItem(new ItemStack(Witchery.Blocks.WALLGEN)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.LIGHT)); + API.hideItem(new ItemStack(Witchery.Blocks.SHADED_GLASS_ON)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.MIRROR)); + API.hideItem(new ItemStack((Block) Witchery.Blocks.MIRROR_UNBREAKABLE)); - API.registerHighlightIdentifier(Witchery.Blocks.TRAPPED_PLANT, (IHighlightHandler)new NEIHighlightHandler(Witchery.Blocks.TRAPPED_PLANT)); - API.registerHighlightIdentifier(Witchery.Blocks.DOOR_ALDER, (IHighlightHandler)new NEIHighlightHandler(Witchery.Blocks.DOOR_ALDER)); - API.registerHighlightIdentifier(Witchery.Blocks.PIT_DIRT, (IHighlightHandler)new NEIHighlightHandler(Witchery.Blocks.PIT_DIRT)); - API.registerHighlightIdentifier(Witchery.Blocks.PIT_GRASS, (IHighlightHandler)new NEIHighlightHandler(Witchery.Blocks.PIT_GRASS)); - WitcheryExtras.log(0, "Done handling NEI related content."); - } + API.registerHighlightIdentifier(Witchery.Blocks.TRAPPED_PLANT, (IHighlightHandler) + new NEIHighlightHandler(Witchery.Blocks.TRAPPED_PLANT)); + API.registerHighlightIdentifier( + Witchery.Blocks.DOOR_ALDER, (IHighlightHandler) new NEIHighlightHandler(Witchery.Blocks.DOOR_ALDER)); + API.registerHighlightIdentifier( + Witchery.Blocks.PIT_DIRT, (IHighlightHandler) new NEIHighlightHandler(Witchery.Blocks.PIT_DIRT)); + API.registerHighlightIdentifier( + Witchery.Blocks.PIT_GRASS, (IHighlightHandler) new NEIHighlightHandler(Witchery.Blocks.PIT_GRASS)); + WitcheryExtras.log(0, "Done handling NEI related content."); + } - public String getName() { - return WitcheryExtras.class.getAnnotation(Mod.class).name(); - } + public String getName() { + return WitcheryExtras.class.getAnnotation(Mod.class).name(); + } - public String getVersion() { - return WitcheryExtras.class.getAnnotation(Mod.class).version(); - } + public String getVersion() { + return WitcheryExtras.class.getAnnotation(Mod.class).version(); + } } diff --git a/src/main/java/alkalus/main/nei/NEI_Handler_Cauldron.java b/src/main/java/alkalus/main/nei/NEI_Handler_Cauldron.java index a9c84d9..90316e5 100644 --- a/src/main/java/alkalus/main/nei/NEI_Handler_Cauldron.java +++ b/src/main/java/alkalus/main/nei/NEI_Handler_Cauldron.java @@ -1,111 +1,137 @@ package alkalus.main.nei; +import codechicken.lib.gui.GuiDraw; +import codechicken.nei.*; import codechicken.nei.recipe.*; -import java.awt.*; -import net.minecraft.client.gui.inventory.*; -import net.minecraft.util.*; import com.emoniph.witchery.brewing.*; import com.emoniph.witchery.brewing.action.*; -import net.minecraft.item.*; -import codechicken.nei.*; +import java.awt.*; +import java.lang.reflect.Field; import java.util.*; +import net.minecraft.client.gui.inventory.*; +import net.minecraft.client.resources.I18n; +import net.minecraft.item.*; +import net.minecraft.util.*; + +public class NEI_Handler_Cauldron extends TemplateRecipeHandler { + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(92, 31, 24, 18), "witchery_brewing_plus", new Object[0])); + } + + public Class getGuiClass() { + return (Class) GuiCrafting.class; + } + + public String getRecipeName() { + return StatCollector.translateToLocal("tile.witchery:cauldron.name"); + } + + public void loadCraftingRecipes(final String outputId, final Object... results) { + if (outputId.equals("witchery_brewing_plus") && this.getClass() == NEI_Handler_Cauldron.class) { + for (final BrewActionRitualRecipe ritual : WitcheryBrewRegistry.INSTANCE.getRecipes()) { + for (final BrewActionRitualRecipe.Recipe recipe : ritual.getExpandedRecipes()) { + this.arecipes.add(new CachedKettleRecipe(recipe.result, recipe.ingredients, getPowerCost(ritual))); + } + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } + + public void loadCraftingRecipes(final ItemStack result) { + for (final BrewActionRitualRecipe ritual : WitcheryBrewRegistry.INSTANCE.getRecipes()) { + for (final BrewActionRitualRecipe.Recipe recipe : ritual.getExpandedRecipes()) { + if (result.isItemEqual(recipe.result)) { + this.arecipes.add(new CachedKettleRecipe(recipe.result, recipe.ingredients, getPowerCost(ritual))); + } + } + } + } + + public void loadUsageRecipes(final ItemStack ingredient) { + for (final BrewActionRitualRecipe ritual : WitcheryBrewRegistry.INSTANCE.getRecipes()) { + try { + for (final BrewActionRitualRecipe.Recipe recipe : ritual.getExpandedRecipes()) { + for (final ItemStack stack : recipe.ingredients) { + if (stack.isItemEqual(ingredient)) { + this.arecipes.add( + new CachedKettleRecipe(recipe.result, recipe.ingredients, getPowerCost(ritual))); + } + } + } + } catch (Throwable t) { + t.printStackTrace(); + } + } + } + + public String getGuiTexture() { + return "witchery:textures/gui/witchesCauldron.png"; + } + + public void drawExtras(final int recipeIndex) { + int power = ((CachedKettleRecipe) this.arecipes.get(recipeIndex)).getPower(); + if (power == 0) { + return; + } + + String text = I18n.format("WitcheryExtras.nei.power", power); + GuiDraw.drawString(text, 5, 54, 0x000000, false); + } + + public String getOverlayIdentifier() { + return "witchery_brewing_plus"; + } + + private AltarPower getPowerCost(BrewAction recipe) { + try { + Field powerCostField = BrewAction.class.getDeclaredField("powerCost"); + powerCostField.setAccessible(true); + return (AltarPower) powerCostField.get(recipe); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public class CachedKettleRecipe extends TemplateRecipeHandler.CachedRecipe { + PositionedStack result; + PositionedStack[] inputs; + int power; + + public CachedKettleRecipe(final ItemStack result, final ItemStack[] recipe, final AltarPower powerCost) { + super(); + this.inputs = new PositionedStack[6]; + this.result = new PositionedStack((Object) result, 119, 31); + for (int i = 0; i < recipe.length; ++i) { + if (recipe[i] != null) { + this.inputs[i] = new PositionedStack((Object) recipe[i], i * 18 + 10, 6); + } else { + this.inputs[i] = null; + } + } + if (powerCost != null) { + this.power = powerCost.getPower(); + } + } + + public PositionedStack getResult() { + return this.result; + } + + public ArrayList getIngredients() { + final ArrayList recipestacks = new ArrayList(); + for (final PositionedStack posStack : this.inputs) { + if (posStack != null) { + recipestacks.add(posStack); + } + } + return recipestacks; + } -public class NEI_Handler_Cauldron extends TemplateRecipeHandler -{ - public void loadTransferRects() { - this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(92, 31, 24, 18), "witchery_brewing_plus", new Object[0])); - } - - public Class getGuiClass() { - return (Class)GuiCrafting.class; - } - - public String getRecipeName() { - return StatCollector.translateToLocal("tile.witchery:cauldron.name"); - } - - public void loadCraftingRecipes(final String outputId, final Object... results) { - if (outputId.equals("witchery_brewing_plus") && this.getClass() == NEI_Handler_Cauldron.class) { - for (final BrewActionRitualRecipe ritual : WitcheryBrewRegistry.INSTANCE.getRecipes()) { - for (final BrewActionRitualRecipe.Recipe recipe : ritual.getExpandedRecipes()) { - this.arecipes.add(new CachedKettleRecipe(recipe.result, recipe.ingredients)); - } - } - } - else { - super.loadCraftingRecipes(outputId, results); - } - } - - public void loadCraftingRecipes(final ItemStack result) { - for (final BrewActionRitualRecipe ritual : WitcheryBrewRegistry.INSTANCE.getRecipes()) { - for (final BrewActionRitualRecipe.Recipe recipe : ritual.getExpandedRecipes()) { - if (result.isItemEqual(recipe.result)) { - this.arecipes.add(new CachedKettleRecipe(recipe.result, recipe.ingredients)); - } - } - } - } - - public void loadUsageRecipes(final ItemStack ingredient) { - for (final BrewActionRitualRecipe ritual : WitcheryBrewRegistry.INSTANCE.getRecipes()) { - try { - for (final BrewActionRitualRecipe.Recipe recipe : ritual.getExpandedRecipes()) { - for (final ItemStack stack : recipe.ingredients) { - if (stack.isItemEqual(ingredient)) { - this.arecipes.add(new CachedKettleRecipe(recipe.result, recipe.ingredients)); - } - } - } - } - catch (Throwable t) { - t.printStackTrace(); - } - } - } - - public String getGuiTexture() { - return "witchery:textures/gui/witchesCauldron.png"; - } - - public void drawExtras(final int recipe) { - } - - public String getOverlayIdentifier() { - return "witchery_brewing_plus"; - } - - public class CachedKettleRecipe extends TemplateRecipeHandler.CachedRecipe - { - PositionedStack result; - PositionedStack[] inputs; - - public CachedKettleRecipe(final ItemStack result, final ItemStack[] recipe) { - super(); - this.inputs = new PositionedStack[6]; - this.result = new PositionedStack((Object)result, 119, 31); - for (int i = 0; i < recipe.length; ++i) { - if (recipe[i] != null) { - this.inputs[i] = new PositionedStack((Object)recipe[i], i * 18 + 10, 6); - } - else { - this.inputs[i] = null; - } - } - } - - public PositionedStack getResult() { - return this.result; - } - - public ArrayList getIngredients() { - final ArrayList recipestacks = new ArrayList(); - for (final PositionedStack posStack : this.inputs) { - if (posStack != null) { - recipestacks.add(posStack); - } - } - return recipestacks; - } - } + public int getPower() { + return this.power; + } + } } diff --git a/src/main/java/alkalus/main/nei/NEI_Handler_Distillery.java b/src/main/java/alkalus/main/nei/NEI_Handler_Distillery.java index a751331..5d0f958 100644 --- a/src/main/java/alkalus/main/nei/NEI_Handler_Distillery.java +++ b/src/main/java/alkalus/main/nei/NEI_Handler_Distillery.java @@ -1,107 +1,103 @@ package alkalus.main.nei; -import codechicken.nei.recipe.*; -import net.minecraft.client.gui.inventory.*; -import com.emoniph.witchery.blocks.*; -import net.minecraft.util.*; - -import com.emoniph.witchery.crafting.*; - import alkalus.main.core.types.Witchery_Distillery; -import alkalus.main.core.util.WitcheryRecipeHandlerInternal; -import net.minecraft.item.*; import codechicken.nei.*; +import codechicken.nei.recipe.*; import com.emoniph.witchery.*; - +import com.emoniph.witchery.blocks.*; +import com.emoniph.witchery.crafting.*; import java.awt.Rectangle; import java.util.*; import java.util.stream.Collectors; +import net.minecraft.client.gui.inventory.*; +import net.minecraft.item.*; +import net.minecraft.util.*; -public class NEI_Handler_Distillery extends TemplateRecipeHandler -{ +public class NEI_Handler_Distillery extends TemplateRecipeHandler { public Class getGuiClass() { return BlockDistilleryGUI.class; } - + public String getRecipeName() { return StatCollector.translateToLocal("tile.witchery:distilleryidle.name"); } - + public void loadTransferRects() { - this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(63, 4, 39, 35), "witchery_distilling", new Object[0])); + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(63, 4, 39, 35), "witchery_distilling", new Object[0])); } - + public void loadCraftingRecipes(final String outputId, final Object... results) { if (outputId.equals("witchery_distilling") && this.getClass() == NEI_Handler_Distillery.class) { - + for (final DistilleryRecipes.DistilleryRecipe recipe : DistilleryRecipes.instance().recipes) { this.arecipes.add(new CachedDistillingRecipe(recipe.outputs[0], recipe)); } - - } - else { + + } else { super.loadCraftingRecipes(outputId, results); } } - - public void loadCraftingRecipes(final ItemStack result) { - List recipes = Witchery_Distillery.findRecipesFor(result); + + public void loadCraftingRecipes(final ItemStack result) { + List recipes = Witchery_Distillery.findRecipesFor(result); for (DistilleryRecipes.DistilleryRecipe recipe : recipes) { - this.arecipes.add(new CachedDistillingRecipe(result, recipe)); + this.arecipes.add(new CachedDistillingRecipe(result, recipe)); } } - + public void loadUsageRecipes(final ItemStack ingredient) { - final DistilleryRecipes.DistilleryRecipe recipe = DistilleryRecipes.instance().findRecipeUsing(ingredient); + final DistilleryRecipes.DistilleryRecipe recipe = + DistilleryRecipes.instance().findRecipeUsing(ingredient); if (recipe != null) { this.arecipes.add(new CachedDistillingRecipe(ingredient, recipe)); } } - + public String getGuiTexture() { return "witchery:textures/gui/distiller.png"; } - + public void drawExtras(final int recipe) { this.drawProgressBar(63, 3, 176, 29, 39, 35, 200, 0); this.drawProgressBar(28, 8, 185, -2, 12, 30, 35, 3); } - + public String getOverlayIdentifier() { return "witchery_distilling"; } - - public class CachedDistillingRecipe extends TemplateRecipeHandler.CachedRecipe - { + + public class CachedDistillingRecipe extends TemplateRecipeHandler.CachedRecipe { PositionedStack ingred1; PositionedStack ingred2; PositionedStack jars; PositionedStack[] outputs; - + public CachedDistillingRecipe(final ItemStack result, final DistilleryRecipes.DistilleryRecipe recipe) { super(); this.outputs = new PositionedStack[6]; - this.ingred1 = new PositionedStack((Object)recipe.inputs[0], 43, 5); + this.ingred1 = new PositionedStack((Object) recipe.inputs[0], 43, 5); if (recipe.inputs[1] != null) { - this.ingred2 = new PositionedStack((Object)recipe.inputs[1], 43, 23); + this.ingred2 = new PositionedStack((Object) recipe.inputs[1], 43, 23); } if (recipe.jars > 0) { - this.jars = new PositionedStack((Object)Witchery.Items.GENERIC.itemEmptyClayJar.createStack(recipe.jars), 43, 43); + this.jars = new PositionedStack( + (Object) Witchery.Items.GENERIC.itemEmptyClayJar.createStack(recipe.jars), 43, 43); } if (recipe.outputs[0] != null) { - this.outputs[0] = new PositionedStack((Object)recipe.outputs[0], 105, 5); + this.outputs[0] = new PositionedStack((Object) recipe.outputs[0], 105, 5); } if (recipe.outputs[1] != null) { - this.outputs[1] = new PositionedStack((Object)recipe.outputs[1], 123, 5); + this.outputs[1] = new PositionedStack((Object) recipe.outputs[1], 123, 5); } if (recipe.outputs[2] != null) { - this.outputs[2] = new PositionedStack((Object)recipe.outputs[2], 105, 23); + this.outputs[2] = new PositionedStack((Object) recipe.outputs[2], 105, 23); } if (recipe.outputs[3] != null) { - this.outputs[3] = new PositionedStack((Object)recipe.outputs[3], 123, 23); + this.outputs[3] = new PositionedStack((Object) recipe.outputs[3], 123, 23); } } - + public PositionedStack getResult() { return null; } diff --git a/src/main/java/alkalus/main/nei/NEI_Handler_Kettle.java b/src/main/java/alkalus/main/nei/NEI_Handler_Kettle.java index 0a8254d..b7bb4ec 100644 --- a/src/main/java/alkalus/main/nei/NEI_Handler_Kettle.java +++ b/src/main/java/alkalus/main/nei/NEI_Handler_Kettle.java @@ -1,46 +1,45 @@ package alkalus.main.nei; +import codechicken.nei.*; import codechicken.nei.recipe.*; +import com.emoniph.witchery.crafting.*; import java.awt.*; +import java.util.*; import net.minecraft.client.gui.inventory.*; -import net.minecraft.util.*; -import com.emoniph.witchery.crafting.*; import net.minecraft.item.*; -import codechicken.nei.*; -import java.util.*; +import net.minecraft.util.*; -public class NEI_Handler_Kettle extends TemplateRecipeHandler -{ +public class NEI_Handler_Kettle extends TemplateRecipeHandler { public void loadTransferRects() { - this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(84, 23, 24, 18), "witchery_brewing", new Object[0])); + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(84, 23, 24, 18), "witchery_brewing", new Object[0])); } - + public Class getGuiClass() { - return (Class)GuiCrafting.class; + return (Class) GuiCrafting.class; } - + public String getRecipeName() { return StatCollector.translateToLocal("tile.witchery:kettle.name"); } - + public void loadCraftingRecipes(final String outputId, final Object... results) { if (outputId.equals("witchery_brewing") && this.getClass() == NEI_Handler_Kettle.class) { for (final KettleRecipes.KettleRecipe recipe : KettleRecipes.instance().recipes) { this.arecipes.add(new CachedKettleRecipe(recipe.output, recipe)); } - } - else { + } else { super.loadCraftingRecipes(outputId, results); } } - + public void loadCraftingRecipes(final ItemStack result) { final KettleRecipes.KettleRecipe recipe = KettleRecipes.instance().findRecipeFor(result); if (recipe != null) { this.arecipes.add(new CachedKettleRecipe(recipe.output, recipe)); } } - + public void loadUsageRecipes(final ItemStack ingredient) { for (final KettleRecipes.KettleRecipe recipe : KettleRecipes.instance().recipes) { if (Arrays.stream(recipe.inputs).anyMatch(ingredient::isItemEqual)) { @@ -48,41 +47,38 @@ public void loadUsageRecipes(final ItemStack ingredient) { } } } - + public String getGuiTexture() { return "textures/gui/container/crafting_table.png"; } - - public void drawExtras(final int recipe) { - } - + + public void drawExtras(final int recipe) {} + public String getOverlayIdentifier() { return "witchery_brewing"; } - - public class CachedKettleRecipe extends TemplateRecipeHandler.CachedRecipe - { + + public class CachedKettleRecipe extends TemplateRecipeHandler.CachedRecipe { PositionedStack result; PositionedStack[] inputs; - + public CachedKettleRecipe(final ItemStack result, final KettleRecipes.KettleRecipe recipe) { super(); this.inputs = new PositionedStack[6]; - this.result = new PositionedStack((Object)result, 119, 24); + this.result = new PositionedStack((Object) result, 119, 24); for (int i = 0; i < recipe.inputs.length; ++i) { if (recipe.inputs[i] != null) { - this.inputs[i] = new PositionedStack((Object)recipe.inputs[i], (i < 3) ? 25 : 43, i * 18 % 54 + 6); - } - else { + this.inputs[i] = new PositionedStack((Object) recipe.inputs[i], (i < 3) ? 25 : 43, i * 18 % 54 + 6); + } else { this.inputs[i] = null; } } } - + public PositionedStack getResult() { return this.result; } - + public ArrayList getIngredients() { final ArrayList recipestacks = new ArrayList(); for (final PositionedStack posStack : this.inputs) { diff --git a/src/main/java/alkalus/main/nei/NEI_Handler_Oven.java b/src/main/java/alkalus/main/nei/NEI_Handler_Oven.java index bd9c400..dc35288 100644 --- a/src/main/java/alkalus/main/nei/NEI_Handler_Oven.java +++ b/src/main/java/alkalus/main/nei/NEI_Handler_Oven.java @@ -1,126 +1,107 @@ package alkalus.main.nei; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import codechicken.nei.recipe.FurnaceRecipeHandler; -import com.emoniph.witchery.Witchery; -import com.emoniph.witchery.blocks.BlockWitchesOvenGUI; - import alkalus.main.core.crafting.OvenRecipes; import alkalus.main.core.crafting.OvenRecipes.OvenRecipe; import alkalus.main.core.util.Utils; -import codechicken.nei.ItemList; import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.FurnaceRecipeHandler; import codechicken.nei.recipe.TemplateRecipeHandler; -import net.minecraft.block.Block; +import com.emoniph.witchery.Witchery; +import com.emoniph.witchery.blocks.BlockWitchesOvenGUI; +import java.awt.Rectangle; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.init.Blocks; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.StatCollector; -public class NEI_Handler_Oven extends TemplateRecipeHandler -{ +public class NEI_Handler_Oven extends TemplateRecipeHandler { public Class getGuiClass() { return BlockWitchesOvenGUI.class; } - + public String getRecipeName() { return StatCollector.translateToLocal("tile.witchery:witchesovenidle.name"); } - + public void loadCraftingRecipes(final String outputId, final Object... results) { if (outputId.equals("witchery_cooking") && this.getClass() == NEI_Handler_Oven.class) { - - final List recipes = OvenRecipes.getRecipeMap(); - for (final OvenRecipe recipe : recipes) { - if (recipe.isValid()) { - final ItemStack input = recipe.inputs.copy(); - final ItemStack output = recipe.output.copy(); - final ItemStack outputJar = recipe.outputJar.copy(); - final SmeltingPair rec = new SmeltingPair( - input, - output, - outputJar); - this.arecipes.add(rec); - } - } - - } - else { + + final List recipes = OvenRecipes.getRecipeMap(); + for (final OvenRecipe recipe : recipes) { + if (recipe.isValid()) { + final ItemStack input = recipe.inputs.copy(); + final ItemStack output = recipe.output.copy(); + final ItemStack outputJar = recipe.outputJar.copy(); + final SmeltingPair rec = new SmeltingPair(input, output, outputJar); + this.arecipes.add(rec); + } + } + + } else { super.loadCraftingRecipes(outputId, results); } } - - public void loadCraftingRecipes(final ItemStack result) { - if (result == null) { - return; - } - final List recipes = OvenRecipes.getRecipeMap(); - for (final OvenRecipe recipe : recipes) { - if (recipe.isValid()) { - final ItemStack input = recipe.inputs.copy(); - final ItemStack output = recipe.output.copy(); - final ItemStack outputJar = recipe.outputJar.copy(); - if (!Utils.areStacksEqual(result, output, true) && !Utils.areStacksEqual(result, outputJar, true)) { - continue; - } - final SmeltingPair rec = new SmeltingPair( - input, - output, - outputJar); - this.arecipes.add(rec); - } - } + + public void loadCraftingRecipes(final ItemStack result) { + if (result == null) { + return; + } + final List recipes = OvenRecipes.getRecipeMap(); + for (final OvenRecipe recipe : recipes) { + if (recipe.isValid()) { + final ItemStack input = recipe.inputs.copy(); + final ItemStack output = recipe.output.copy(); + final ItemStack outputJar = recipe.outputJar.copy(); + if (!Utils.areStacksEqual(result, output, true) && !Utils.areStacksEqual(result, outputJar, true)) { + continue; + } + final SmeltingPair rec = new SmeltingPair(input, output, outputJar); + this.arecipes.add(rec); + } + } } - + public void loadUsageRecipes(final String inputId, final Object... ingredients) { if (inputId.equals("fuel") && this.getClass() == NEI_Handler_Oven.class) { this.loadCraftingRecipes("witchery_cooking", new Object[0]); - } - else { + } else { super.loadUsageRecipes(inputId, ingredients); } } - + public void loadUsageRecipes(final ItemStack ingredient) { - final List recipes = OvenRecipes.getRecipeMap(); - if (ingredient != null) { - //Logger.INFO("Looking up Usage results for "+ItemUtils.getItemName(ingredient)); - } - for (final OvenRecipe recipe : recipes) { - if (recipe.isValid()) { - final ItemStack input = recipe.inputs.copy(); - final ItemStack output = recipe.output.copy(); - final ItemStack outputJar = recipe.outputJar.copy(); - if (!Utils.areStacksEqual(ingredient, input, true) && !Utils.areStacksEqual(ingredient, Witchery.Items.GENERIC.itemEmptyClayJar.createStack(), true)) { - continue; - } - final SmeltingPair rec = new SmeltingPair( - input, - output, - outputJar); - this.arecipes.add(rec); - } - } - + final List recipes = OvenRecipes.getRecipeMap(); + if (ingredient != null) { + // Logger.INFO("Looking up Usage results for "+ItemUtils.getItemName(ingredient)); + } + for (final OvenRecipe recipe : recipes) { + if (recipe.isValid()) { + final ItemStack input = recipe.inputs.copy(); + final ItemStack output = recipe.output.copy(); + final ItemStack outputJar = recipe.outputJar.copy(); + if (!Utils.areStacksEqual(ingredient, input, true) + && !Utils.areStacksEqual( + ingredient, Witchery.Items.GENERIC.itemEmptyClayJar.createStack(), true)) { + continue; + } + final SmeltingPair rec = new SmeltingPair(input, output, outputJar); + this.arecipes.add(rec); + } + } } - + public String getGuiTexture() { return "witchery:textures/gui/witchesOven.png"; } - + public void loadTransferRects() { - this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(50, 23, 18, 18), "fuel", new Object[0])); - this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(74, 9, 24, 18), "witchery_cooking", new Object[0])); + this.transferRects.add( + new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(50, 23, 18, 18), "fuel", new Object[0])); + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(74, 9, 24, 18), "witchery_cooking", new Object[0])); } @Override @@ -132,46 +113,48 @@ public void drawExtras(final int recipe) { this.drawProgressBar(51, 25, 176, 0, 14, 14, 48, 7); this.drawProgressBar(74, 9, 176, 14, 24, 16, 48, 0); } - + public String getOverlayIdentifier() { return "witchery_cooking"; } - + public TemplateRecipeHandler newInstance() { return super.newInstance(); } - - public class SmeltingPair extends TemplateRecipeHandler.CachedRecipe - { + + public class SmeltingPair extends TemplateRecipeHandler.CachedRecipe { PositionedStack ingred; PositionedStack result; PositionedStack byproduct; PositionedStack jar; - + public SmeltingPair(final ItemStack ingred, final ItemStack result, final ItemStack byproduct) { super(); ingred.stackSize = 1; - this.ingred = new PositionedStack((Object)ingred, 51, 6); - this.result = new PositionedStack((Object)result, 113, 10); - this.byproduct = new PositionedStack((Object)byproduct, 113, 42); - this.jar = new PositionedStack((Object)Witchery.Items.GENERIC.itemEmptyClayJar.createStack(), 78, 42); + this.ingred = new PositionedStack((Object) ingred, 51, 6); + this.result = new PositionedStack((Object) result, 113, 10); + this.byproduct = new PositionedStack((Object) byproduct, 113, 42); + this.jar = new PositionedStack((Object) Witchery.Items.GENERIC.itemEmptyClayJar.createStack(), 78, 42); } - + public List getIngredients() { - return (List)this.getCycledIngredients(NEI_Handler_Oven.this.cycleticks / 48, (List)Arrays.asList(this.ingred)); + return (List) + this.getCycledIngredients(NEI_Handler_Oven.this.cycleticks / 48, (List) Arrays.asList(this.ingred)); } - + public PositionedStack getResult() { return this.result; } - + public PositionedStack getOtherStack() { if (FurnaceRecipeHandler.afuels != null && FurnaceRecipeHandler.afuels.size() > 0) { - return FurnaceRecipeHandler.afuels.get(NEI_Handler_Oven.this.cycleticks / 48 % FurnaceRecipeHandler.afuels.size()).stack; + return FurnaceRecipeHandler.afuels.get( + NEI_Handler_Oven.this.cycleticks / 48 % FurnaceRecipeHandler.afuels.size()) + .stack; } return null; } - + public List getOtherStacks() { final ArrayList stacks = new ArrayList(); final PositionedStack stack = this.getOtherStack(); @@ -183,14 +166,13 @@ public List getOtherStacks() { return stacks; } } - - public static class FuelPair - { + + public static class FuelPair { public PositionedStack stack; public int burnTime; - + public FuelPair(final ItemStack ingred, final int burnTime) { - this.stack = new PositionedStack((Object)ingred, 51, 42); + this.stack = new PositionedStack((Object) ingred, 51, 42); this.burnTime = burnTime; } } diff --git a/src/main/java/alkalus/main/nei/NEI_Handler_SpinningWheel.java b/src/main/java/alkalus/main/nei/NEI_Handler_SpinningWheel.java index 1761cca..2c0ac57 100644 --- a/src/main/java/alkalus/main/nei/NEI_Handler_SpinningWheel.java +++ b/src/main/java/alkalus/main/nei/NEI_Handler_SpinningWheel.java @@ -1,93 +1,91 @@ package alkalus.main.nei; +import codechicken.nei.*; import codechicken.nei.recipe.*; -import net.minecraft.client.gui.inventory.*; import com.emoniph.witchery.blocks.*; -import net.minecraft.util.*; -import java.awt.*; import com.emoniph.witchery.crafting.*; -import net.minecraft.item.*; -import codechicken.nei.*; +import java.awt.*; import java.util.*; +import net.minecraft.client.gui.inventory.*; +import net.minecraft.item.*; +import net.minecraft.util.*; -public class NEI_Handler_SpinningWheel extends TemplateRecipeHandler -{ +public class NEI_Handler_SpinningWheel extends TemplateRecipeHandler { public Class getGuiClass() { return BlockSpinningWheelGUI.class; } - + public String getRecipeName() { return StatCollector.translateToLocal("tile.witchery:spinningwheel.name"); } - + public void loadTransferRects() { - this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(74, 9, 24, 18), "witchery_spinning", new Object[0])); + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(74, 9, 24, 18), "witchery_spinning", new Object[0])); } - + public void loadCraftingRecipes(final String outputId, final Object... results) { if (outputId.equals("witchery_spinning") && this.getClass() == NEI_Handler_SpinningWheel.class) { for (final SpinningRecipes.SpinningRecipe recipe : SpinningRecipes.instance().recipes) { this.arecipes.add(new CachedSpinningRecipe(recipe.getResult(), recipe)); } - } - else { + } else { super.loadCraftingRecipes(outputId, results); } } - + public void loadCraftingRecipes(final ItemStack result) { final SpinningRecipes.SpinningRecipe recipe = SpinningRecipes.instance().findRecipeFor(result); if (recipe != null) { this.arecipes.add(new CachedSpinningRecipe(result, recipe)); } } - + public void loadUsageRecipes(final ItemStack ingredient) { final SpinningRecipes.SpinningRecipe recipe = SpinningRecipes.instance().findRecipeUsing(ingredient); if (recipe != null) { this.arecipes.add(new CachedSpinningRecipe(ingredient, recipe)); } } - + public String getGuiTexture() { return "witchery:textures/gui/spinningwheel.png"; } - + public void drawExtras(final int recipe) { this.drawProgressBar(51, 25, 176, 0, 14, 14, 48, 7); } - + public String getOverlayIdentifier() { return "witchery_spinning"; } - - public class CachedSpinningRecipe extends TemplateRecipeHandler.CachedRecipe - { + + public class CachedSpinningRecipe extends TemplateRecipeHandler.CachedRecipe { PositionedStack fibre; PositionedStack output; PositionedStack add1; PositionedStack add2; PositionedStack add3; - + public CachedSpinningRecipe(final ItemStack result, final SpinningRecipes.SpinningRecipe recipe) { super(); - this.fibre = new PositionedStack((Object)recipe.fibre, 51, 9); - this.output = new PositionedStack((Object)recipe.getResult(), 113, 9); + this.fibre = new PositionedStack((Object) recipe.fibre, 51, 9); + this.output = new PositionedStack((Object) recipe.getResult(), 113, 9); if (recipe.modifiers.length > 0 && recipe.modifiers[0] != null) { - this.add1 = new PositionedStack((Object)recipe.modifiers[0], 51, 42); + this.add1 = new PositionedStack((Object) recipe.modifiers[0], 51, 42); } if (recipe.modifiers.length > 1 && recipe.modifiers[1] != null) { - this.add2 = new PositionedStack((Object)recipe.modifiers[1], 69, 42); + this.add2 = new PositionedStack((Object) recipe.modifiers[1], 69, 42); } if (recipe.modifiers.length > 2 && recipe.modifiers[2] != null) { - this.add3 = new PositionedStack((Object)recipe.modifiers[2], 87, 42); + this.add3 = new PositionedStack((Object) recipe.modifiers[2], 87, 42); } } - + public PositionedStack getResult() { return this.output; } - + public ArrayList getIngredients() { final ArrayList recipestacks = new ArrayList(); recipestacks.add(this.fibre); diff --git a/src/main/java/com/emoniph/witchery/integration/NEIWitcheryConfig.java b/src/main/java/com/emoniph/witchery/integration/NEIWitcheryConfig.java index 2991ab3..4012458 100644 --- a/src/main/java/com/emoniph/witchery/integration/NEIWitcheryConfig.java +++ b/src/main/java/com/emoniph/witchery/integration/NEIWitcheryConfig.java @@ -4,8 +4,7 @@ public class NEIWitcheryConfig { - static { - Logger.ASM("Static loading dummy class to appease the gods of Java stack."); - } - + static { + Logger.ASM("Static loading dummy class to appease the gods of Java stack."); + } } diff --git a/src/main/resources/assets/WitcheryExtras/lang/en_US.lang b/src/main/resources/assets/WitcheryExtras/lang/en_US.lang index 59442ea..5eecb71 100644 --- a/src/main/resources/assets/WitcheryExtras/lang/en_US.lang +++ b/src/main/resources/assets/WitcheryExtras/lang/en_US.lang @@ -1,4 +1,6 @@ tile.witchesovenexidle.name=Witches Oven tile.witchesovenexburning.name=Witches Oven (Active) tile.fumefunnelex.name=Fume Funnel -tile.filteredfumefunnelex.name=Filtered Fume Funnel \ No newline at end of file +tile.filteredfumefunnelex.name=Filtered Fume Funnel + +WitcheryExtras.nei.power=Power required: %s \ No newline at end of file